Skip to content

[PERF] games.py O(n²) fork detection algorithms #20

Description

@galpt

Issue

In cog/games.py#L302-L337, the check_fork_opportunities() and check_block_fork() functions have nested loops resulting in O(n²) complexity:

def check_fork_opportunities(self):
    for idx in empty:  # O(n) where n is empty cells
        self.board[idx] = bot_mark
        for i in range(self.size * self.size):  # O(n) nested!
            # ...

Why This Is a Problem

For a 5x5 board with 25 cells, this results in 625 iterations per strategy check. With multiple strategy checks (check_immediate_win, check_block_player, check_fork_opportunities, check_block_fork), this adds up.


How to Fix

Consider caching board state analysis or pre-computing valid move positions. However, for typical board sizes (3x3, 5x5), this is likely not a major concern unless boards get much larger.

If boards are small, you could add a comment explaining the complexity is acceptable for the use case, or refactor to avoid repeated nested iterations.


Severity

Medium - Potential performance issue for larger boards

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions