KatInterview

Identify Winning Move in Bottom-Inserted Drop Game

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designarrayshash-tablesimulation

Last 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], where turn_number is the 1-based index of the turn that created the win, and winners is 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$
  • player is 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.