Identify Winning Move in Bottom-Inserted Drop Game
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a custom grid game with bottom-insertion pushes to detect the earliest turn that forms a line of length k.
In a grid game played on an infinite upper half-plane, two participants—B and R—take turns placing tokens into integer-indexed columns ($\dots, -2, -1, 0, 1, 2, \dots$). Rows are indexed starting from the base row $0$ and extend infinitely upward ($0, 1, 2, \dots$).
Unlike standard drop games where pieces fall from the top, tokens are inserted from the bottom:
- If a token is dropped into an empty column, it rests at row $0$.
- If a column already holds tokens, every existing token in that column is shifted up by 1 row, and the newly added token occupies row $0$.
Insertion into a column does not modify adjacent columns.
A player achieves a win when $k$ adjacent cells along a single horizontal row or a single vertical column contain only that player's tokens. Diagonal sequences are ignored. Because inserting a token elevates an entire column, a single turn can simultaneously realign tokens across multiple rows, potentially triggering wins for one or both players on the same turn.
Given an integer $k$ and a sequential list of turns, process each action in order. As soon as at least one winning alignment of length $k$ is formed:
- Stop processing subsequent turns immediately.
- Return
[turn_number, winners], whereturn_numberis the 1-based index of the turn that created the win, andwinnersis a list of player names ("B","R", or both sorted alphabetically["B", "R"]) who hold a qualifying line of length $k$.
If all turns complete without any player forming a $k$-length sequence, return [-1, []].
Constraints
- $1 \le k \le 50$
- $1 \le \text{len}(moves) \le 5000$
- $-10^6 \le \text{column} \le 10^6$
playeris always"B"or"R".
Examples
Example 1
Input: detect_first_winner(3, [['B', 0], ['R', 5], ['B', 1], ['R', 5], ['B', 2]])
Output: [5, ['B']]
Example 2
Input: detect_first_winner(3, [['R', -1], ['B', -1], ['R', 0], ['B', 0], ['R', 1], ['B', 1]])
Output: [6, ['B', 'R']]
Example 3
Input: detect_first_winner(3, [['B', 0], ['R', 0], ['B', 0]])
Output: [-1, []]
Hints
Hint 1
The coordinate space for columns is wide (-10^6 to 10^6), so use dynamic hash structures rather than a rigid 2D grid.
Hint 2
When a token is inserted into column c, every token previously in column c shifts upward by 1 row. Ensure you clear old row bindings before adding the shifted ones to avoid row-index overwrites.
Hint 3
Check all newly modified or moved cells after each turn: the vertical line starting at row 0 of column c, and horizontal spans centered at each displaced row in column c.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires simulating a game where pieces are pushed into the bottom of a column (row 0), shifting all pre-existing pieces in that column upward by one unit.
Because the column boundaries are unbounded ($\pm 10^6$), maintaining a static 2D grid is inefficient. Instead, we maintain two sparse structures:
column_stacks: A dictionary mapping each column to a list of tokens ordered from bottom (row 0) to top.row_maps: A dictionary mapping each row index to a hash map{col: token}representing pieces residing on that row.
Incremental State Maintenance
When a token for player is inserted into col:
- Clear old row registrations: Iterate over rows $0 \dots h-1$ for column
col(where $h$ is the prior height) and deletecolfromrow_maps[r]. - Apply row shift: Re-insert each shifted token into
row_maps[r + 1][col]. - Insert base token: Set
row_maps[0][col] = playerand updatecolumn_stacks[col]by prependingplayer.
Win Verification
After each move, any newly formed winning run must pass through one of the modified cells:
- Vertical checks: Check if the first $k$ elements in
column_stacks[col]are identical. - Horizontal checks: Each affected row $r \in [0, h]$ in column
colhas a piece at(r, col). We expand horizontally to the left and right inrow_maps[r]to count matching contiguous pieces.
If any line reaches length $\ge k$, add that piece's owner to a set of victors. If victors is non-empty after checking all affected positions, we return [turn_number, sorted(victors)].
Complexity
- Time Complexity: $\mathcal{O}(N \cdot H \cdot k)$, where $N$ is the number of moves and $H$ is the max height of a column. In practice, $H \le N$, making the worst-case runtime $\mathcal{O}(N^2 \cdot k)$. Given $N = 5000$ and $k \le 50$, sparse operations execute well within reasonable limits.
- Space Complexity: $\mathcal{O}(N)$, as at most $N$ tokens are placed across all dictionaries.
Solution Code
from typing import List
def detect_first_winner(k: int, moves: List[List[object]]) -> List[object]:
column_stacks = {}
row_maps = {}
for turn_idx, (player, col) in enumerate(moves, 1):
prev_stack = column_stacks.get(col, [])
stack_len = len(prev_stack)
# Remove previous instances of this column's entries from row structures
for r in range(stack_len):
r_dict = row_maps[r]
del r_dict[col]
if not r_dict:
del row_maps[r]
# Shift old tokens up by one row
for r, token in enumerate(prev_stack):
row_maps.setdefault(r + 1, {})[col] = token
# Insert new token at row 0
column_stacks[col] = [player] + prev_stack
row_maps.setdefault(0, {})[col] = player
victors = set()
# Check for vertical win at column `col` starting from row 0
if len(column_stacks[col]) >= k:
bottom_token = column_stacks[col][0]
if all(t == bottom_token for t in column_stacks[col][:k]):
victors.add(bottom_token)
# Check horizontal wins across all affected rows in column `col`
updated_cells = [(0, player)] + [(r + 1, token) for r, token in enumerate(prev_stack)]
for r_idx, token in updated_cells:
current_row = row_maps[r_idx]
consecutive = 1
# Look left
left_col = col - 1
while current_row.get(left_col) == token:
consecutive += 1
left_col -= 1
# Look right
right_col = col + 1
while current_row.get(right_col) == token:
consecutive += 1
right_col += 1
if consecutive >= k:
victors.add(token)
if victors:
return [turn_idx, sorted(list(victors))]
return [-1, []]