Board Game: Detect k-in-a-Row on a Rectangular Grid
Data Structure DesignAuto-graded · 24 test casesLast updated
Tests incremental win detection on an m×n board by tracking consecutive run lengths at endpoints to check for k-in-a-row in O(1) per move.
You are building the core logic for a two-player grid game on an m × n board. A player wins by placing k of their marks in an unbroken line through any newly placed piece.
Given the board dimensions, the win length, and a sequence of moves, return the result of each move: the winning player's id if that move ends the game, or 0 if the game is still ongoing after that move.
The Game
The board has m rows and n columns, with positions indexed from (0, 0) at the top-left. Two players, identified as 1 and 2, take turns placing marks. A move is a triple (row, col, player). Players are not guaranteed to alternate turns.
A move is a winning move if, once the mark is placed, that player has at least k of their own marks in an unbroken sequence passing through the newly placed cell. The sequence may run horizontally, vertically, along the main diagonal (top-left to bottom-right), or along the anti-diagonal (top-right to bottom-left). A run of length strictly greater than k still counts as a win.
Input
m— number of rowsn— number of columnsk— number of consecutive marks needed to winmoves— a list of(row, col, player)triples
Output
A list of integers with exactly one entry per move, in order. Each entry is player if that move wins the game, or 0 otherwise. No move is ever given after a winning move, so the game ends either with a win or with the board partially filled and no winner.
Constraints
1 <= m, n <= 10001 <= k <= max(m, n)1 <= len(moves) <= min(m * n, 10^5)- Every move is valid: the cell is within bounds, unoccupied, and
playeris1or2 - No move is provided after a winning move
Examples
Example 1
Input: play_grid_game(3, 3, 3, [[0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]])
Output: [0, 0, 0, 0, 0, 0, 1]
Example 2
Input: play_grid_game(4, 5, 3, [[0, 4, 2], [3, 0, 1], [1, 3, 2], [0, 0, 1], [2, 2, 2]])
Output: [0, 0, 0, 0, 2]
Example 3
Input: play_grid_game(2, 4, 4, [[0, 0, 1], [1, 0, 2], [0, 1, 1], [1, 1, 2], [0, 2, 1], [1, 2, 2], [0, 3, 1]])
Output: [0, 0, 0, 0, 0, 0, 1]
Hints
Hint 1
Start with the simpler O(k) approach: after placing a mark, scan outward in each of the 4 directions up to k−1 steps on each side and count how far the same player's marks extend. This is correct and worth coding first before optimizing.
Hint 2
To reach O(1) per move, think about what information you'd need already stored so you don't have to scan. For a run of consecutive marks, which cells actually need to hold the run's length? You don't need every cell to be accurate — only the ones you'll read next time.
Hint 3
The key insight: store the run length at both endpoints of every maximal run. When you place a new mark, its immediate same-player neighbors (if any) must be endpoints of their respective runs, because the cell you just filled was empty a moment ago. Read those stored lengths, add them together with 1 for the new mark, and write the merged length to the new endpoints.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Naive baseline: scan outward — O(k) per move
After placing a mark at (row, col), walk outward in each of the 4 line directions (horizontal, vertical, main diagonal, anti-diagonal). On each side, step up to k − 1 cells and count how far the same player's marks extend without a gap or an opponent's mark. If the two sides together with the placed cell reach k, the move wins.
This is straightforward and correct, but costs O(k) per move. With k up to 1 000 and 10^5 moves, that is up to 8 × 10^8 steps in Python — too slow for large inputs.
O(1) per move: store run length at endpoints only
The key observation is that you never need to know a run's length from an interior cell — only from the cells adjacent to an empty gap. When a new mark is placed at x, the cell was empty until now, so any same-player neighbor of x in a given direction must be at the end of its run. It is an endpoint.
Invariant: for every maximal consecutive run of one player's marks in each direction, both endpoint cells store the run's exact length. Interior cells may hold stale values, but they are never read.
Per move, per direction:
- Check the immediate neighbor one step behind
x. If it belongs to the same player, read its stored run length (left). Otherwiseleft = 0. - Do the same one step ahead to get
right. - The merged run has length
total = left + 1 + right. - Write
totaltoxand to the two new far endpoints (the old back-end and the old front-end of the merged run). - If
total >= kfor any direction, the move wins.
Why reads are safe. The placed cell was empty, so both neighbors are endpoints by the invariant. Their stored values are exact run lengths, not stale interior values.
Why writes maintain the invariant. After the merge, the new maximal run's endpoints are the two far cells. We write total there. The old inner endpoints are now interior and will never be read again.
Edge cases covered by this structure — no special-casing needed:
k = 1:totalis at least 1, so the first move always wins.- Single row or column: directions pointing off the board always contribute 0.
klarger than a board dimension (e.g.,k = 4on a 2-row board): vertical runs can never reachk; the check simply never triggers in that direction.- Non-alternating players: everything is per-move and per-player with no assumption about turn order.
- A mark filling a gap between two existing runs (e.g.,
X X _ X Xwithk = 5):leftandrightare both non-zero, and the merged total catches it directly. - Overlines (
total > k): the condition is>= k, so longer runs win correctly. - Flat-index safety: the column bounds check (
0 <= c < n) prevents a step in the horizontal direction from wrapping into the adjacent row.
Complexity
- Time: O(m·n) to initialize, then O(1) per move (4 directions, constant work each). Total: O(m·n + len(moves)).
- Space: O(m·n) for the
ownerarray and 4 run arrays. At the given constraints that is 5 arrays of up to 10^6 integers — acceptable, and worth mentioning to an interviewer. If memory is tight, replace the flat arrays with dictionaries keyed by occupied cells, reducing space to O(len(moves)) at a small constant-factor cost.
Full solution
from typing import List, Tuple
def play_grid_game(m: int, n: int, k: int, moves: List[Tuple[int, int, int]]) -> List[int]:
size = m * n
owner = [0] * size # 0 = empty, 1 or 2 = player
runs = [[0] * size for _ in range(4)] # run length stored at endpoints
dirs = ((0, 1), (1, 0), (1, 1), (1, -1)) # horizontal, vertical, main diag, anti-diag
out = []
for row, col, player in moves:
x = row * n + col
owner[x] = player
won = False
for d in range(4):
dr, dc = dirs[d]
rd = runs[d]
# Length of the same-player run ending just behind the placed cell.
r2, c2 = row - dr, col - dc
left = 0
if 0 <= r2 < m and 0 <= c2 < n and owner[r2 * n + c2] == player:
left = rd[r2 * n + c2]
# Length of the same-player run starting just ahead of the placed cell.
r3, c3 = row + dr, col + dc
right = 0
if 0 <= r3 < m and 0 <= c3 < n and owner[r3 * n + c3] == player:
right = rd[r3 * n + c3]
total = left + 1 + right
# Write the merged run length to the placed cell and both new endpoints.
rd[x] = total
rd[(row - left * dr) * n + (col - left * dc)] = total
rd[(row + right * dr) * n + (col + right * dc)] = total
if total >= k:
won = True
out.append(player if won else 0)
return out