Implement Connect Four with win detection
Company: Airbnb
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates a candidate's ability to design efficient data structures and algorithms for real-time game state management, including win detection, API design, time/space complexity analysis, and handling edge cases such as full or out-of-range columns.
Constraints
- 1 <= m, n <= 200
- 1 <= k <= max(m, n)
- 0 <= len(operations) <= 10^5
- Players are identified by integers 1 and 2
Examples
Input: (6, 7, 4, [("move", 0, 1), ("move", 1, 2), ("move", 0, 1), ("move", 1, 2), ("move", 0, 1), ("move", 1, 2), ("move", 0, 1), ("isDraw",)])
Expected Output: [0, 0, 0, 0, 0, 0, 1, False]
Explanation: Player 1 stacks four discs in column 0 and wins vertically on the seventh operation. The board is not full, so isDraw returns False.
Input: (4, 4, 4, [("move", 0, 1), ("move", 1, 2), ("move", 1, 1), ("move", 2, 2), ("move", 2, 2), ("move", 2, 1), ("move", 3, 2), ("move", 3, 2), ("move", 3, 2), ("move", 3, 1), ("move", 0, 2), ("undo",), ("move", 0, 2)])
Expected Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, True, 0]
Explanation: Player 1 forms a diagonal from bottom-left to top-right on move 10. A later move is invalid because the game is already over. Undo removes the winning move, and the final move becomes legal again.
Input: (2, 2, 2, [("move", -1, 1), ("move", 2, 1), ("move", 0, 1), ("move", 0, 2), ("move", 0, 1), ("reset",), ("move", 1, 2), ("isDraw",)])
Expected Output: [-1, -1, 0, 0, -1, None, 0, False]
Explanation: Columns -1 and 2 are out of range. After two valid moves, column 0 becomes full, so another move there is invalid. Reset clears the board, and the new move succeeds.
Input: (2, 2, 3, [("move", 0, 1), ("move", 0, 2), ("move", 1, 1), ("move", 1, 2), ("isDraw",), ("undo",), ("isDraw",)])
Expected Output: [0, 0, 0, 0, True, True, False]
Explanation: With k = 3 on a 2 x 2 board, no one can win. After four moves the board is full, so it is a draw. Undo removes the last move, so it is no longer a draw.
Input: (1, 4, 4, [("move", 0, 1), ("move", 1, 1), ("move", 2, 1), ("move", 3, 1), ("move", 0, 2)])
Expected Output: [0, 0, 0, 1, -1]
Explanation: On a single-row board, player 1 makes four in a row horizontally. Any later move is invalid because the game has already ended.
Hints
- Keep an array of the next free row for each column so a move does not need to search downward.
- After placing a disc, only four directions through that cell matter: horizontal, vertical, diagonal down-right, and diagonal down-left.