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 for player (1 or 2) on cell (row, col).
  • Every placement is valid: (row, col) lies inside the m x n grid and has not been occupied earlier. Players do not necessarily alternate turns.
  • A placement wins immediately if, once placed, player owns an unbroken contiguous streak of at least k of 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 (1 or 2) for a winning placement and 0 otherwise.
  • No further placements appear in moves once someone wins. Return a list[int] of length len(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 <= 1000
  • 1 <= k <= max(m, n)
  • 1 <= len(moves) <= min(m * n, 10^5)
  • 0 <= row < m, 0 <= col < n, and player is 1 or 2

Step-by-step walkthrough

  1. Understand the board, the four winning lines, and the turn rules

    We are given board dimensions m x n, a target streak length k, and a sequence of valid moves (row, col, player). After each move, we return player (1 or 2) if that move completes at least k consecutive marks for that player, or 0 otherwise.

    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 player from the move tuple, never from the move index. - Any unbroken streak of length >= k wins: Placing a mark into a gap between two existing runs can jump from 2 and 2 straight to 5, which still wins when k = 3 or k = 4. - Any diagonal can win, not just corner-to-corner: On a 3 x 6 board with k = 3, off-center diagonals of length 3 are valid winning lines.

  2. Why rescanning the board or walking outward can be too slow

    Scanning the entire m x n board after every move takes O(m * n) time per move — up to 10^11 operations for 10^5 moves on a 1000 x 1000 grid. Note also that the classic 3 x 3 Tic-Tac-Toe trick of keeping a single counter per row/column fails when k < n, because 1 1 2 1 has three 1s in the same row without 3 in 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 is back_len + 1 + forward_len. Walking outward cell by cell takes O(k) time per move, which works for small k, yet on a 1000 x 1000 board with k = 1000, building long rows of 999 marks across 10^5 moves still performs roughly 5 * 10^7 inner-loop steps. Can we find back_len and forward_len in O(1) time without walking at all?

  3. 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 to player, it was sitting next to an empty square, so it must be the right endpoint of player's run on the left — meaning its stored length is completely up to date! Symmetrically, if the neighbor right after (row, col) belongs to player, it must be the left endpoint of player'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!

  4. Represent sparse board state with dictionaries

    We store the board in sparse dictionaries keyed by (row, col) rather than allocating m x n 2D lists: - self.owner[(row, col)]: which player (1 or 2) occupies (row, col). - self.run_length[direction_idx][(row, col)]: the run length along DIRECTIONS[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 from self.owner, so self.owner.get(cell) returns None instead of wrapping around the end of a Python list (grid[0][-1]). 2. Memory scales with moves, not board area: Even on a 1000 x 1000 board with 5 moves, we store only 5 cells.

    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]
    
  5. Code the O(1) move update and game runner

    Inside move(row, col, player), we record self.owner[(row, col)] = player and update all four directions: 1. Read back_len at (row - dr, col - dc) and forward_len at (row + dr, col + dc). 2. Compute merged_len = back_len + 1 + forward_len. 3. Step back_len units backward to start_end = (row - back_len * dr, col - back_len * dc) and forward_len units forward to finish_end = (row + forward_len * dr, col + forward_len * dc), and write merged_len to both. Notice that when back_len == 0 and forward_len == 0 (an isolated mark), both start_end and finish_end equal (row, col), storing 1 at (row, col) with zero special cases! 4. Check merged_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 results
    
  6. Trace 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 on direction_idx = 3, the anti-diagonal (dr, dc) = (1, -1) where prev_cell is up-right (row - 1, col + 1) and next_cell is 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 2
    

    No other axis reaches 3 on the earlier moves (Move 5 makes a vertical pair of 1s at (0, 0) and (1, 0) of length 2 < 3), so the output is [0, 0, 0, 0, 0, 2].

  7. 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 to move inserts one entry into owner and loops over exactly 4 directions, performing 2 dictionary lookups and 2 dictionary writes per direction (16 hash-table operations total, independent of m, n, and k).
  • Space: O(M). Neither __init__ nor move allocates an m x n grid; owner stores at most M occupied coordinates, and each of the four run_length dictionaries stores entries only at occupied coordinates (<= M keys each).

Edge cases

  • k = 1 (including 1 x 1 boards): On the very first move, back_len = 0 and forward_len = 0 give merged_len = 1 >= 1, returning the first mover immediately.
  • Bridging a gap between two runs: Placing a mark between two runs of length 2 produces 2 + 1 + 2 = 5, winning for k = 5 (and also winning for k = 3 or k = 4 because we test >= k).
  • Opponent marks splitting a line: In 1 1 2 1 1, (0, 2) belongs to player 2, so _run_ending_at returns 0 when player 1 queries it, keeping player 1's runs separate at length 2.
  • Board edges and corners: Coordinates outside 0 .. m - 1 or 0 .. n - 1 are never placed into owner, so _run_ending_at returns 0 automatically with no wraparound across rows or opposite edges.
  • Rectangular boards where some axes are shorter than k: On a 2 x 3 board with k = 3 (Example 3), vertical and diagonal runs naturally cap out at length 2 and never reach 3, while horizontal runs can reach 3.
  • 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.k instead of >= self.k: Joining two runs of 2 creates a run of 5, skipping right over 3 and 4.
  • Checking only the two corner-to-corner diagonals (row == col and row + col == n - 1): On an m x n board — or whenever k < min(m, n) — any diagonal of length at least k can hold a winning line (for example, (3, 0) and (4, 1) on a 5 x 2 board with k = 2).
  • Updating run_length at (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 >= 0 checks: In Python, grid[row][col - 1] when col == 0 silently reads grid[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 inside 0 <= r < m, 0 <= c < n and match player, stopping early once count == k. Requires only the owner board (O(M) or O(m * n) memory) and zero extra bookkeeping, trading O(1) move time for O(k) worst-case move time.
  • Per-window mark counters: Maintain (p1_count, p2_count) for every contiguous k-cell window horizontally, vertically, and diagonally; a window becomes dead once both players occupy it, and wins when one player reaches k. Costs O(k) per move and O(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 in O(1) time? Every call to move modifies owner[(row, col)] plus at most 8 entries in run_length (start_end and finish_end across 4 directions). Before overwriting those 8 dictionary 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 previous run_length values (or deletes keys that were previously absent), and deletes owner[cell] in O(1) time.
  • How would you return the exact coordinates of the winning k-in-a-row segment? Inside move, the winning axis (dr, dc) already computes start_end = (row - back_len * dr, col - back_len * dc) and finish_end = (row + forward_len * dr, col + forward_len * dc). Every step (start_r + step * dr, start_c + step * dc) for step from 0 to merged_len - 1 belongs to player, so you can immediately slice any k consecutive coordinates (or return the full merged_len line).
  • What if the board is infinite or 10^9 x 10^9 and almost empty? Our dictionary-based TicTacToe class already handles an unbounded or 10^9 x 10^9 board with zero code changes! Because owner and run_length hash (row, col) tuples only for played moves and never allocate an m x n array, both memory (O(M)) and per-move runtime (O(1)) depend solely on the number of moves played.

Follow-up questions

Similar questions

More Databricks interview questions

All 122 Databricks questions →