Four in a row: check a winning move
Two players, "a" and "b", play on a rectangular grid. board is a 2D list of strings; each cell is "a", "b", or "" (empty).
Implement:
def is_winning_move(board: list[list[str]], move: tuple[int, int], player: str) -> bool
move = (row, col) is the cell where player places a piece. Return True if, after the piece is placed, player has four or more consecutive pieces in a line that goes through that cell: horizontally, vertically, or along either diagonal. Otherwise return False.
Treat the move cell as player's piece whether it is currently empty or already holds that piece. Raise an error if the move is off the board, the cell holds the other player's piece, or player is not "a" or "b".
Constraints: the board is at least 1x1 and can be large. Aim for work that does not grow with the board size.
Example 1
board = [
["", "", "", "" ],
["", "b", "", "" ],
["", "", "b", "" ],
["", "", "", "b"],
]
is_winning_move(board, (0, 0), "b") -> True # main diagonal
is_winning_move(board, (0, 0), "a") -> False
Example 2
board = [["a", "", "a", "a", "b"]]
is_winning_move(board, (0, 1), "a") -> True # fills the gap: a a a a
is_winning_move(board, (0, 1), "b") -> False
Likely next parts: add gravity and alternating turns (pieces drop to the lowest empty row of a column), generalize to k in a row, and detect a draw.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
