k-Streak Win Detection on a Rectangular Grid
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Simulate a two-player connection game on a 0-indexed m x n grid where a player wins by forming k consecutive tokens along a straight line:
def play_tic_tac_toe(m: int, n: int, k: int, moves: list[tuple[int, int, int]]) -> list[int]:
In an interactive interview setting, this game is structured around a stateful TicTacToe(m, n, k) class whose move(row, col, player) -> int method processes one placement at a time. Here, play_tic_tac_toe initializes an empty m x n grid, executes every placement in moves in order, and returns the list of per-move outcomes.
Follow these game rules:
- Each tuple
(row, col, player)places a token forplayer(1or2) on cell(row, col). - Every placement is valid:
(row, col)lies inside them x ngrid and has not been occupied earlier. Players do not necessarily alternate turns. - A placement wins immediately if, once placed,
playerowns an unbroken contiguous streak of at leastkof their own tokens passing through(row, col)horizontally, vertically, along a downward-right diagonal ((+1, +1)), or along a downward-left diagonal ((+1, -1)). - Return
player(1or2) for a winning placement and0otherwise. - No further placements appear in
movesonce someone wins. Return alist[int]of lengthlen(moves)in placement order.
Examples
Example 1
Input:
m = 4, n = 4, k = 3
moves = [(1, 0, 1), (0, 0, 2), (1, 2, 1), (0, 3, 2), (1, 1, 1)]
Output:
[0, 0, 0, 0, 1]
Walk-through: Player 1 places tokens at (1, 0) and (1, 2) first, then fills the middle gap (1, 1) on the fifth turn to link (1, 0), (1, 1), and (1, 2) into a horizontal line of length 3.
Example 2
Input:
m = 3, n = 6, k = 3
moves = [(0, 4, 2), (0, 0, 1), (2, 2, 2), (2, 5, 1), (1, 0, 1), (1, 3, 2)]
Output:
[0, 0, 0, 0, 0, 2]
Walk-through: Turns need not alternate (player 1 takes both the fourth and fifth turns). On the sixth turn, player 2 places at (1, 3), bridging (0, 4) and (2, 2) into a length-3 anti-diagonal.
Example 3
Input:
m = 2, n = 3, k = 3
moves = [(0, 0, 1), (0, 1, 2), (1, 0, 2), (1, 1, 1), (0, 2, 1), (1, 2, 2)]
Output:
[0, 0, 0, 0, 0, 0]
Walk-through: On a 2 x 3 grid, vertical and diagonal lines contain at most 2 cells, and neither row reaches 3 matching tokens ([1, 2, 1] and [2, 1, 2]), so every turn returns 0.
Constraints
1 <= m, n <= 10001 <= k <= max(m, n)1 <= len(moves) <= min(m * n, 10^5)0 <= row < m,0 <= col < n, andplayeris1or2
Step-by-step walkthrough
Understand the board, the four winning lines, and the turn rules
We are given board dimensions
m x n, a target streak lengthk, and a sequence of valid moves(row, col, player). After each move, we returnplayer(1or2) if that move completes at leastkconsecutive marks for that player, or0otherwise.Every line passing through
(row, col)follows one of four axes: - Horizontal:(0, +1)and(0, -1)(left and right along the row) - Vertical:(+1, 0)and(-1, 0)(down and up along the column) - Main diagonal:(+1, +1)and(-1, -1)(top-left to bottom-right) - Anti-diagonal:(+1, -1)and(-1, +1)(top-right to bottom-left)(-1, -1) (-1, 0) (-1, +1) \ | / (0, -1) -- (row, col) -- (0, +1) / | \ (+1, -1) (+1, 0) (+1, +1)Keep three crucial rules in mind: - Players need not alternate: Always read
playerfrom the move tuple, never from the move index. - Any unbroken streak of length>= kwins: Placing a mark into a gap between two existing runs can jump from2and2straight to5, which still wins whenk = 3ork = 4. - Any diagonal can win, not just corner-to-corner: On a3 x 6board withk = 3, off-center diagonals of length3are valid winning lines.Why rescanning the board or walking outward can be too slow
Scanning the entire
m x nboard after every move takesO(m * n)time per move — up to10^11operations for10^5moves on a1000 x 1000grid. Note also that the classic3 x 3Tic-Tac-Toe trick of keeping a single counter per row/column fails whenk < n, because1 1 2 1has three1s in the same row without3in a row!A much better start is to notice that only the four lines passing through
(row, col)can gain a new win. Along each axis, the new run length isback_len + 1 + forward_len. Walking outward cell by cell takesO(k)time per move, which works for smallk, yet on a1000 x 1000board withk = 1000, building long rows of999marks across10^5moves still performs roughly5 * 10^7inner-loop steps. Can we findback_lenandforward_leninO(1)time without walking at all?Key idea: store each run's length at its two outer endpoints
Fix one axis (say horizontal). A run is a maximal unbroken stretch of consecutive marks belonging to the same player. Instead of updating every cell inside a run when it grows, we maintain one simple invariant: every maximal run stores its exact length at its two outer endpoint cells.
Why is that enough? Because every move is guaranteed to land on an empty square
(row, col)! If the neighbor right before(row, col)belongs toplayer, it was sitting next to an empty square, so it must be the right endpoint ofplayer's run on the left — meaning its stored length is completely up to date! Symmetrically, if the neighbor right after(row, col)belongs toplayer, it must be the left endpoint ofplayer's run on the right:Before placing player 1 at col 2 (k = 5): col: 0 1 2 3 4 owner: [ 1 | 1 | . | 1 | 1 ] run_length: 2 2 2 2 ^ ^ back_len = 2 forward_len = 2 (both neighbors are outer endpoints!) After placing player 1 at col 2: merged_len = 2 + 1 + 2 = 5 start_end = col - back_len = 2 - 2 = 0 finish_end = col + forward_len = 2 + 2 = 4 col: 0 1 2 3 4 owner: [ 1 | 1 | 1 | 1 | 1 ] run_length: 5 (2) . (2) 5 ^ ^ outer endpoints updated to 5!What about the interior cells (
col 1,col 2,col 3) that still hold old numbers or nothing? Both neighbors of an interior cell are already occupied, and marks are never erased, so no future valid move can ever land next to an interior cell and read its stale value!Represent sparse board state with dictionaries
We store the board in sparse dictionaries keyed by
(row, col)rather than allocatingm x n2D lists: -self.owner[(row, col)]: which player (1or2) occupies(row, col). -self.run_length[direction_idx][(row, col)]: the run length alongDIRECTIONS[direction_idx]when(row, col)is an outer endpoint of a run.Using dictionaries gives us two big advantages: 1. Zero bounds-check bugs: Off-board coordinates like
(-1, 5)or(0, -1)are simply absent fromself.owner, soself.owner.get(cell)returnsNoneinstead of wrapping around the end of a Python list (grid[0][-1]). 2. Memory scales with moves, not board area: Even on a1000 x 1000board with5moves, we store only5cells.from typing import Any, Dict, List, Optional, Set, Tuple # Four line axes: horizontal (0, 1), vertical (1, 0), main diagonal (1, 1), anti-diagonal (1, -1). DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)] class TicTacToe: def __init__(self, m: int, n: int, k: int): # Off-board cells are never inserted into `owner`, so `m` and `n` need no explicit check. self.k = k # owner: dict mapping (row, col) -> player_id (1 or 2) for occupied cells only self.owner: Dict[Tuple[int, int], int] = {} # run_length[d]: dict mapping (row, col) -> int length of the contiguous run along DIRECTIONS[d]. # Invariant: only the two outer endpoint cells of each maximal run are guaranteed up to date. self.run_length: List[Dict[Tuple[int, int], int]] = [{}, {}, {}, {}] def _run_ending_at(self, direction_idx: int, cell: Tuple[int, int], player: int) -> int: """Return length of `player`'s run along `direction_idx` ending at `cell`, or 0 if not theirs.""" if self.owner.get(cell) != player: return 0 return self.run_length[direction_idx][cell]Code the O(1) move update and game runner
Inside
move(row, col, player), we recordself.owner[(row, col)] = playerand update all four directions: 1. Readback_lenat(row - dr, col - dc)andforward_lenat(row + dr, col + dc). 2. Computemerged_len = back_len + 1 + forward_len. 3. Stepback_lenunits backward tostart_end = (row - back_len * dr, col - back_len * dc)andforward_lenunits forward tofinish_end = (row + forward_len * dr, col + forward_len * dc), and writemerged_lento both. Notice that whenback_len == 0andforward_len == 0(an isolated mark), bothstart_endandfinish_endequal(row, col), storing1at(row, col)with zero special cases! 4. Checkmerged_len >= self.k.def move(self, row: int, col: int, player: int) -> int: self.owner[(row, col)] = player won = False # Check and merge contiguous runs along each of the four axes through (row, col). for direction_idx, (dr, dc) in enumerate(DIRECTIONS): # Because (row, col) was empty before this move, any adjacent cell owned by `player` # is guaranteed to be an outer endpoint of its existing run, holding an exact length. prev_cell = (row - dr, col - dc) next_cell = (row + dr, col + dc) back_len = self._run_ending_at(direction_idx, prev_cell, player) forward_len = self._run_ending_at(direction_idx, next_cell, player) merged_len = back_len + 1 + forward_len # Write the merged run length to both new outer endpoints of the combined run. start_end = (row - back_len * dr, col - back_len * dc) finish_end = (row + forward_len * dr, col + forward_len * dc) self.run_length[direction_idx][start_end] = merged_len self.run_length[direction_idx][finish_end] = merged_len # Use `>=` rather than `==` because bridging two runs can jump straight past `k`. if merged_len >= self.k: won = True if won: return player return 0 def play_tic_tac_toe(m: int, n: int, k: int, moves: list[tuple[int, int, int]]) -> list[int]: game = TicTacToe(m, n, k) results = [] for row, col, player in moves: results.append(game.move(row, col, player)) return resultsTrace Example 2 along the anti-diagonal
Let's trace Example 2 (
m = 3, n = 6, k = 3) with moves[(0, 4, 2), (0, 0, 1), (2, 2, 2), (2, 5, 1), (1, 0, 1), (1, 3, 2)], focusing ondirection_idx = 3, the anti-diagonal(dr, dc) = (1, -1)whereprev_cellis up-right(row - 1, col + 1)andnext_cellis down-left(row + 1, col - 1):Board after all 6 moves: col: 0 1 2 3 4 5 r=0: 1 . . . 2 . <-- Move 1: (0, 4, p2) r=1: 1 . . 2 . . <-- Move 6: (1, 3, p2) bridges (0, 4) and (2, 2) into length 3! r=2: . . 2 . . 1 <-- Move 3: (2, 2, p2) Anti-diagonal (dr=1, dc=-1) trace: Move 1 (0, 4, p2): prev=(-1, 5)->0, next=(1, 3)->0 => merged=1, write 1 at (0, 4) -> returns 0 Move 2 (0, 0, p1): prev=(-1, 1)->0, next=(1,-1)->0 => merged=1, write 1 at (0, 0) -> returns 0 Move 3 (2, 2, p2): prev=(1, 3)->0, next=(3, 1)->0 => merged=1, write 1 at (2, 2) -> returns 0 Move 4 (2, 5, p1): prev=(1, 6)->0, next=(3, 4)->0 => merged=1, write 1 at (2, 5) -> returns 0 Move 5 (1, 0, p1): prev=(0, 1)->0, next=(2,-1)->0 => merged=1, write 1 at (1, 0) -> returns 0 Move 6 (1, 3, p2): prev=(0, 4)->1, next=(2, 2)->1 => merged = 1 + 1 + 1 = 3 >= k=3! write 3 at (0, 4) & (2, 2) -> returns 2No other axis reaches
3on the earlier moves (Move 5 makes a vertical pair of1s at(0, 0)and(1, 0)of length2 < 3), so the output is[0, 0, 0, 0, 0, 2].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Four line axes: horizontal (0, 1), vertical (1, 0), main diagonal (1, 1), anti-diagonal (1, -1). DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)] class TicTacToe: def __init__(self, m: int, n: int, k: int): # Off-board cells are never inserted into `owner`, so `m` and `n` need no explicit check. self.k = k # owner: dict mapping (row, col) -> player_id (1 or 2) for occupied cells only self.owner: Dict[Tuple[int, int], int] = {} # run_length[d]: dict mapping (row, col) -> int length of the contiguous run along DIRECTIONS[d]. # Invariant: only the two outer endpoint cells of each maximal run are guaranteed up to date. self.run_length: List[Dict[Tuple[int, int], int]] = [{}, {}, {}, {}] def _run_ending_at(self, direction_idx: int, cell: Tuple[int, int], player: int) -> int: """Return length of `player`'s run along `direction_idx` ending at `cell`, or 0 if not theirs.""" if self.owner.get(cell) != player: return 0 return self.run_length[direction_idx][cell] def move(self, row: int, col: int, player: int) -> int: self.owner[(row, col)] = player won = False # Check and merge contiguous runs along each of the four axes through (row, col). for direction_idx, (dr, dc) in enumerate(DIRECTIONS): # Because (row, col) was empty before this move, any adjacent cell owned by `player` # is guaranteed to be an outer endpoint of its existing run, holding an exact length. prev_cell = (row - dr, col - dc) next_cell = (row + dr, col + dc) back_len = self._run_ending_at(direction_idx, prev_cell, player) forward_len = self._run_ending_at(direction_idx, next_cell, player) merged_len = back_len + 1 + forward_len # Write the merged run length to both new outer endpoints of the combined run. start_end = (row - back_len * dr, col - back_len * dc) finish_end = (row + forward_len * dr, col + forward_len * dc) self.run_length[direction_idx][start_end] = merged_len self.run_length[direction_idx][finish_end] = merged_len # Use `>=` rather than `==` because bridging two runs can jump straight past `k`. if merged_len >= self.k: won = True if won: return player return 0 def play_tic_tac_toe(m: int, n: int, k: int, moves: list[tuple[int, int, int]]) -> list[int]: game = TicTacToe(m, n, k) results = [] for row, col, player in moves: results.append(game.move(row, col, player)) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine snapping toy train cars onto numbered slots along a track and wanting to know instantly how long a connected train has become whenever a new car drops into an empty gap. Instead of walking from car to car to recount the train every turn, you write the train's total length on a tag attached only to its front and back cars — a technique called endpoint run-length tracking (storing the length of each maximal contiguous streak of identical marks at its two boundary cells). Because every valid move lands on an empty square, any neighboring square of the same player right next to it was sitting beside that empty gap and is therefore guaranteed to be an outer boundary of an existing streak! We check all four line axes through (row, col) — horizontal, vertical, main diagonal (sloping down-and-right with step (+1, +1)), and anti-diagonal (sloping down-and-left with step (+1, -1)) — reading the two neighbors' lengths and writing back_len + 1 + forward_len to the two new outer ends in O(1) time.
Why do simpler approaches fall short? Rescanning the whole m x n grid after every move costs O(m * n) per move (10^11 operations for 10^5 moves on a 1000 x 1000 grid), and the classic n x n Tic-Tac-Toe trick of keeping one sum per row/column breaks completely whenever k < n because X X O X has three Xs in the row without three consecutive marks. Even walking outward from (row, col) along the four axes costs O(k) per move, which can still perform ~5 * 10^7 steps when k = 1000 and long streaks accumulate across 10^5 moves.
Here is how a single gap-filling move at (0, 2) for player 1 (k = 4) merges two horizontal streaks in O(1) time:
1. Before move (0, 2, player=1):
col: 0 1 2 3
owner: [ 1 | 1 | . | 1 ]
horiz len: 2 2 1 <-- col 1 (end of [0..1]) stores 2; col 3 (end of [3..3]) stores 1
2. Place player 1 at (0, 2):
- back_len at (0, 1) = 2, forward_len at (0, 3) = 1
- merged_len = 2 + 1 + 1 = 4 (>= k = 4 -> WIN!)
- Update outer ends only: start_end = (0, 2 - 2) = (0, 0) -> 4
finish_end = (0, 2 + 1) = (0, 3) -> 4
Complexity
Let M be the number of moves (len(moves)).
- Time:
O(1)average per move,O(M)total. Every call tomoveinserts one entry intoownerand loops over exactly4directions, performing2dictionary lookups and2dictionary writes per direction (16hash-table operations total, independent ofm,n, andk). - Space:
O(M). Neither__init__normoveallocates anm x ngrid;ownerstores at mostMoccupied coordinates, and each of the fourrun_lengthdictionaries stores entries only at occupied coordinates (<= Mkeys each).
Edge cases
k = 1(including1 x 1boards): On the very first move,back_len = 0andforward_len = 0givemerged_len = 1 >= 1, returning the first mover immediately.- Bridging a gap between two runs: Placing a mark between two runs of length
2produces2 + 1 + 2 = 5, winning fork = 5(and also winning fork = 3ork = 4because we test>= k). - Opponent marks splitting a line: In
1 1 2 1 1,(0, 2)belongs to player2, so_run_ending_atreturns0when player1queries it, keeping player1's runs separate at length2. - Board edges and corners: Coordinates outside
0 .. m - 1or0 .. n - 1are never placed intoowner, so_run_ending_atreturns0automatically with no wraparound across rows or opposite edges. - Rectangular boards where some axes are shorter than
k: On a2 x 3board withk = 3(Example 3), vertical and diagonal runs naturally cap out at length2and never reach3, while horizontal runs can reach3. - Non-alternating turns: All state is keyed by explicit
(cell, player)ownership rather than turn parity.
Common mistakes
- Counting only one direction from
(row, col): Looking only left or only right misses wins where the new move drops into the middle of two partial runs. - Checking
merged_len == self.kinstead of>= self.k: Joining two runs of2creates a run of5, skipping right over3and4. - Checking only the two corner-to-corner diagonals (
row == colandrow + col == n - 1): On anm x nboard — or wheneverk < min(m, n)— any diagonal of length at leastkcan hold a winning line (for example,(3, 0)and(4, 1)on a5 x 2board withk = 2). - Updating
run_lengthat(row, col)instead of(start_end, finish_end): Leaving stale counts at the far ends of the merged run causes a later move at the far end to undercount the streak. - Indexing a 2D Python list without
>= 0checks: In Python,grid[row][col - 1]whencol == 0silently readsgrid[row][-1](the rightmost column!), making the left and right edges wrap around like a cylinder.
Alternative approaches
- Walk outward along the 4 axes on each move: Starting at
(row, col), step forward and backward along each(dr, dc)while cells stay inside0 <= r < m,0 <= c < nand matchplayer, stopping early oncecount == k. Requires only theownerboard (O(M)orO(m * n)memory) and zero extra bookkeeping, tradingO(1)move time forO(k)worst-case move time. - Per-window mark counters: Maintain
(p1_count, p2_count)for every contiguousk-cell window horizontally, vertically, and diagonally; a window becomes dead once both players occupy it, and wins when one player reachesk. CostsO(k)per move andO(m * n)space, and is handy when you also want to detect guaranteed draws before the board fills up.
Follow-up questions
- How would you support an
undo()method for the most recent move inO(1)time? Every call tomovemodifiesowner[(row, col)]plus at most8entries inrun_length(start_endandfinish_endacross4directions). Before overwriting those8dictionary slots, save a small change record(cell, [(d, pos, old_val), ...])onto a stack (a last-in, first-out list where the most recent item is popped first);undo()simply pops that record, restores the previousrun_lengthvalues (or deletes keys that were previously absent), and deletesowner[cell]inO(1)time. - How would you return the exact coordinates of the winning
k-in-a-row segment? Insidemove, the winning axis(dr, dc)already computesstart_end = (row - back_len * dr, col - back_len * dc)andfinish_end = (row + forward_len * dr, col + forward_len * dc). Every step(start_r + step * dr, start_c + step * dc)forstepfrom0tomerged_len - 1belongs toplayer, so you can immediately slice anykconsecutive coordinates (or return the fullmerged_lenline). - What if the board is infinite or
10^9 x 10^9and almost empty? Our dictionary-basedTicTacToeclass already handles an unbounded or10^9 x 10^9board with zero code changes! Becauseownerandrun_lengthhash(row, col)tuples only for played moves and never allocate anm x narray, both memory (O(M)) and per-move runtime (O(1)) depend solely on the number of moves played.
Follow-up questions
- How would you support an `undo()` method for the most recent move in `O(1)` time?
- How would you return the exact coordinates of the winning `k`-in-a-row segment?
- What if the board is infinite or `10^9 x 10^9` and almost empty?
Similar questions
- Insertion-Ordered Set with O(1) Snapshot Iterators
- Ordered Allow/Deny Cancellation of an IPv4 CIDR
- Minimum Travel Time Across a Speed-Limited Grid
- Five-Minute Window Average for Streaming Load
- Trailing Five-Minute In-Memory QPS Tracker
- Minimal CIDR Cover for an IPv4 Range
More Databricks interview questions
- Referral-Aware Customer Revenue Tracker Medium
- First Anagram Substring Index Medium
- Snapshot-Isolated Dynamic Set Hard Pro
- Bounded-Memory Rolling Hit Counter Medium Pro
- Background Intro, Workplace Disagreement, and Flagship Project Medium Pro
- Key-Value Store with Sliding-Window Read and Write Rates Medium Pro
- Behavioral Recruiter Screen Medium Pro
- Trailing Five-Minute In-Memory QPS Tracker Medium Pro
- Bounded-Ply Forced Win Search on Generalized Tic-Tac-Toe Medium Pro
- Enterprise Messaging Core: Sequenced Timelines and Versioned Membership Hard Pro