Bird
Raised Fist0
LLDsystem_design~25 mins

Special moves (castling, en passant) in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Chess Special Moves Handler
Design focuses on the logic and architecture for handling special chess moves castling and en passant within a chess game system. It excludes UI design and full chess engine implementation.
Functional Requirements
FR1: Support castling move with all rules validation (king and rook unmoved, no check on path, no pieces between)
FR2: Support en passant move with correct capture logic and timing (only immediately after opponent pawn moves two squares)
FR3: Integrate with existing chess game state and move validation system
FR4: Provide clear feedback on move legality
FR5: Allow querying current special move availability per player
Non-Functional Requirements
NFR1: Must respond to move validation requests within 50ms
NFR2: Handle up to 1000 concurrent games in memory
NFR3: Ensure correctness and consistency of game state after special moves
NFR4: Availability target 99.9% uptime for move validation service
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Game state manager
Move validator module
Special moves handler component
Event or command processor for moves
In-memory cache or database for game states
Design Patterns
State machine pattern for game state transitions
Command pattern for move execution
Observer pattern for notifying move results
Rule engine or strategy pattern for move validation
Reference Architecture
  +-------------------+       +---------------------+       +---------------------+
  |                   |       |                     |       |                     |
  |  Game State Store +<----->+  Special Moves       +<----->+  Move Validator      |
  |  (In-memory DB)   |       |  Handler Component   |       |  Module              |
  |                   |       |                     |       |                     |
  +-------------------+       +---------------------+       +---------------------+
           ^                            ^                             ^
           |                            |                             |
           |                            |                             |
           +----------------------------+-----------------------------+
                                        |
                                +----------------+
                                | Client / UI    |
                                +----------------+
Components
Game State Store
In-memory data structure or Redis
Stores current board positions, piece states, move history, and flags for special moves eligibility
Special Moves Handler Component
Custom logic module in chosen language
Encapsulates rules and validation logic for castling and en passant moves
Move Validator Module
Service or library
Validates all moves including special moves by consulting game state and special moves handler
Client / UI
Chess frontend or API consumer
Sends move requests and receives validation results
Request Flow
1. Client sends a move request to the Move Validator Module.
2. Move Validator queries Game State Store for current board and move history.
3. Move Validator calls Special Moves Handler to check if move is castling or en passant and validate rules.
4. Special Moves Handler checks conditions: for castling, verifies king and rook unmoved, path clear, no check; for en passant, verifies last move was opponent pawn two squares, target square correct.
5. Special Moves Handler returns validation result to Move Validator.
6. Move Validator returns final move legality to Client.
7. If move is valid and special, Game State Store updates board and flags accordingly.
Database Schema
Entities: - Game: id, current_turn, status - BoardState: game_id, piece_positions (map of square to piece), move_history (list of moves) - PieceState: piece_id, has_moved (boolean), position - SpecialMoveFlags: game_id, castling_rights (per player and side), en_passant_target_square, en_passant_valid_turn Relationships: - Game 1:1 BoardState - BoardState 1:N PieceState - Game 1:1 SpecialMoveFlags
Scaling Discussion
Bottlenecks
Game State Store memory usage grows with number of concurrent games
Move Validator latency increases with complex validation logic
Concurrency conflicts when multiple moves processed simultaneously for same game
Solutions
Use efficient in-memory data structures and evict finished games to reduce memory
Optimize validation logic with caching and early exits for common cases
Implement locking or transactional updates per game to avoid race conditions
Interview Tips
Time: Spend 10 minutes clarifying requirements and constraints, 20 minutes designing components and data flow, 10 minutes discussing scaling and trade-offs, 5 minutes summarizing.
Explain how special moves have unique rules requiring dedicated logic
Describe how game state tracks piece movement and special flags
Show clear separation of concerns between validation and state management
Discuss concurrency and consistency challenges in multi-game environment
Mention latency and availability targets and how design meets them

Practice

(1/5)
1. Which of the following conditions must be true for castling to be allowed in a chess game?
easy
A. The king is currently in check and moves two squares towards the rook.
B. Neither the king nor the rook involved has moved before, and no pieces are between them.
C. The rook has moved once, but the king has not moved.
D. The king moves diagonally two squares towards the rook.

Solution

  1. Step 1: Understand castling rules

    Castling requires that neither the king nor the rook involved has moved before, and the squares between them are empty.
  2. Step 2: Check king safety conditions

    The king cannot be in check, nor can it pass through or land on a square under attack during castling.
  3. Final Answer:

    Neither the king nor the rook involved has moved before, and no pieces are between them. -> Option B
  4. Quick Check:

    Castling conditions = Neither the king nor the rook involved has moved before, and no pieces are between them. [OK]
Hint: Castling needs unmoved king and rook with clear path [OK]
Common Mistakes:
  • Allowing castling when king is in check
  • Ignoring if rook has moved
  • Allowing king to move diagonally during castling
2. Which code snippet correctly checks if an en passant move is possible in a chess game for an opponent pawn landing to the right?
easy
A. if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (1, 0): allow_en_passant()
B. if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (0, -1): allow_en_passant()
C. if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (0, 1): allow_en_passant()
D. if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (-1, 0): allow_en_passant()

Solution

  1. Step 1: Understand en passant position logic

    En passant capture happens when an opponent's pawn moves two squares forward and lands beside your pawn horizontally.
  2. Step 2: Identify correct position offset

    The opponent pawn must be exactly one square horizontally adjacent (x+1 or x-1), so position + (1, 0) is correct for right side.
  3. Final Answer:

    if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (1, 0): allow_en_passant() -> Option A
  4. Quick Check:

    En passant horizontal check = if pawn.just_moved_two_squares and opponent_pawn.position == pawn.position + (1, 0): allow_en_passant() [OK]
Hint: En passant checks horizontal adjacency after two-step pawn move [OK]
Common Mistakes:
  • Checking vertical instead of horizontal adjacency
  • Using wrong coordinate offsets
  • Ignoring the two-square move condition
3. Given this simplified code snippet for castling validation, what will be the output if the king has moved before?
def can_castle(king_moved, rook_moved, path_clear):
    if king_moved or rook_moved:
        return False
    if not path_clear:
        return False
    return True

print(can_castle(True, False, True))
medium
A. None
B. True
C. False
D. Error

Solution

  1. Step 1: Analyze input parameters

    king_moved is True, rook_moved is False, path_clear is True.
  2. Step 2: Follow function logic

    Since king_moved is True, the first if condition triggers and returns False immediately.
  3. Final Answer:

    False -> Option C
  4. Quick Check:

    King moved disables castling = False [OK]
Hint: If king moved, castling returns False immediately [OK]
Common Mistakes:
  • Ignoring king_moved condition
  • Assuming path_clear overrides king_moved
  • Expecting True despite king having moved
4. Identify the bug in this en passant validation code snippet:
def can_en_passant(pawn_pos, opponent_pawn_pos, last_move):
    if last_move == 'two_squares_forward' and abs(pawn_pos[0] - opponent_pawn_pos[0]) == 1:
        return True
    return False

# Example call
print(can_en_passant((4,4), (5,4), 'two_squares_forward'))
medium
A. The function should return False when pawns are adjacent.
B. The function incorrectly compares x-coordinates instead of y-coordinates.
C. The last_move parameter should be a boolean, not a string.
D. The function does not check if pawns are on the same rank (y-coordinate).

Solution

  1. Step 1: Understand en passant position requirements

    En passant requires pawns to be on the same rank (same y-coordinate) and adjacent files (x-coordinates differ by 1).
  2. Step 2: Analyze code logic

    The code checks x-coordinate difference but does not verify if y-coordinates are equal, missing a key condition.
  3. Final Answer:

    The function does not check if pawns are on the same rank (y-coordinate). -> Option D
  4. Quick Check:

    Missing same rank check = The function does not check if pawns are on the same rank (y-coordinate). [OK]
Hint: En passant needs same rank check besides adjacency [OK]
Common Mistakes:
  • Ignoring y-coordinate equality
  • Assuming x difference alone suffices
  • Misusing last_move parameter type
5. You are designing a chess game system that supports castling and en passant. Which design approach best ensures correct validation of these special moves while keeping the system scalable?
hard
A. Track each piece's move history and board state; validate special moves by checking move history and current board conditions.
B. Only check the current board state without tracking move history, assuming special moves are rare.
C. Allow special moves without validation to simplify the system and fix errors later.
D. Hardcode special move rules without tracking piece movement or board state.

Solution

  1. Step 1: Understand requirements for special moves

    Castling and en passant depend on move history (e.g., whether king or rook moved, or if pawn moved two squares last turn) and current board state.
  2. Step 2: Evaluate design options

    Tracking move history and board state allows accurate validation and supports scalability as game complexity grows.
  3. Final Answer:

    Track each piece's move history and board state; validate special moves by checking move history and current board conditions. -> Option A
  4. Quick Check:

    Move history + board state = correct scalable validation [OK]
Hint: Track moves and board state for reliable special move validation [OK]
Common Mistakes:
  • Ignoring move history for special moves
  • Hardcoding rules without flexibility
  • Skipping validation to simplify design