Gravity Grid: Pushing Tokens Up from Below and Spotting Matching Lines
Arrays & HashingAuto-graded · 21 test casesLast updated
Simulate a grid where tokens are pushed in from the bottom of a column, and after each push report success and whether any full column or full row is single-typed.
Gravity Grid: Pushing Tokens Up from Below and Spotting Matching Lines
A grid has R rows and C columns. Every cell is either empty or contains a token of type "A" or "B". Row 0 is the bottom row and row R - 1 is the top row. Columns are numbered 0 to C - 1.
How tokens enter
Tokens are always pushed in from the bottom of a column:
- Pushing a token into column
cmoves every token already in that column up by one row, and the new token is placed in row0of columnc. - As a result, the tokens in any column always fill rows
0, 1, ..., k - 1for somek, with no gaps. - If column
calready containsRtokens, the push fails and the grid is left exactly as it was.
Task
You are given a list of pushes. Each push is a pair [c, p]: push a token of type p into column c. After handling every push, successful or not, record three booleans describing the grid at that moment:
ok:trueif the push succeeded,falseif it failed because columncwas full.uniform_column:trueif at least one column is completely full (allRcells occupied) and all its tokens have the same type; otherwisefalse.uniform_row:trueif at least one row is completely full (allCcells occupied) and all its tokens have the same type; otherwisefalse.
Return the list of these triples, one for each push, in the order the pushes were given.
Details
- A column that is only partly filled never counts as uniform, even if all its current tokens match.
- A row that is only partly filled never counts as uniform. Row
ris completely filled exactly when every column holds more thanrtokens. - After a failed push, the grid is unchanged, so
uniform_columnanduniform_rowmust equal their values from the grid state before that push. - A row that was uniform can stop being uniform after a push, because the push shifts tokens in one column upward. The flags must reflect the grid as it is right now.
Input
R: number of rows.C: number of columns.ops: list of pushes, each[c, p]with column indexcand token typep("A"or"B").
Output
A list with one entry per push, each entry being [ok, uniform_column, uniform_row] with boolean values, describing the grid right after that push.
Constraints
1 <= R <= 501 <= C <= 501 <= len(ops) <= 10^40 <= c < Cpis either"A"or"B"
Examples
Example 1
Input: simulate_gravity_grid(2, 2, [[0, 'A'], [1, 'A'], [0, 'B'], [1, 'B'], [1, 'A']])
Output: [[True, False, False], [True, False, True], [True, False, False], [True, False, True], [False, False, True]]
Hints
Hint 1
Store each column as a list where index r is the token in row r. A push is then an insertion at index 0, and a column is full when its length equals R.
Hint 2
Row r is completely filled only if every column has more than r tokens. Only then compare the tokens at index r across all columns.
Hint 3
A brute-force scan of the whole grid after each push is about 2.5 * 10^7 cell checks in total at the limits, which is fine. For a faster version, note that a full column never changes again, so its uniformity only needs to be decided once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store each column as a list in which index r is the token in row r. A push inserts at index 0, which shifts the others up. A push succeeds only if the column has fewer than R tokens.
The simple method rescans the whole grid after every push. It checks every column for "full and all the same" and every row for "full and all the same". That is O(R * C) per push, about 2.5 * 10^7 cell checks in total at the limits, which is acceptable.
A faster method uses two observations.
Column uniformity only ever turns on. A column changes only while it is not full. Once full, all later pushes into it fail, so its contents are frozen. We therefore decide its verdict once, when its length reaches R. We keep a count of A tokens per column; at that moment the column is uniform exactly when the count is 0 or R. We count uniform full columns, and uniform_column is count > 0.
Row bookkeeping touches only the affected rows. A push into column c with old length k changes the column-c entries of rows 0..k only. For each row we maintain:
fill[r]: the number of columns with more thanrtokens. Rowris fully occupied exactly whenfill[r] == C.cnt_a[r]: the number ofAtokens in rowr.
On a successful push, subtract the old contributions of the column to cnt_a for rows 0..k-1, insert the token, add the new contributions for rows 0..k, and increment fill[k]. A full row is uniform exactly when cnt_a[r] is 0 (all B) or C (all A). The row flag is recomputed by scanning the R rows, since it can switch back to false when a shift breaks a uniform row.
A failed push changes nothing, so we output false together with the previous two flags.
Why it is correct
- Tokens in a column always occupy rows
0..len-1, so rowris complete exactly when every column is longer thanr. When a column grows fromktok + 1, only rowkbecomes newly covered, sofillstays exact. - After the shift, we remove every old contribution of the column and add every new one, so
cnt_astays exact for every row. Other columns are unaffected. - In a full row the
AandBcounts add up toC, so "all the same type" is equivalent tocnt_a[r]being0orC. - Full columns never change, so deciding their uniformity once is equivalent to checking all columns after each push.
Complexity
- Time:
O(R)per push, soO(len(ops) * R)overall. - Space:
O(R * C)for the grid plusO(R + C)for the counters.
Reference solution
from typing import List
def simulate_gravity_grid(R: int, C: int, ops: List[List[object]]) -> List[List[bool]]:
cols = [[] for _ in range(C)] # cols[c][r] is the token in row r of column c
col_a = [0] * C # count of "A" tokens per column
fill = [0] * R # fill[r] = number of columns with more than r tokens
cnt_a = [0] * R # cnt_a[r] = number of "A" tokens in row r
uniform_cols = 0 # number of full uniform columns (never decreases)
uc = False
ur = False
results = []
for c, p in ops:
col = cols[c]
k = len(col)
if k >= R:
results.append([False, uc, ur])
continue
# remove old row contributions of this column
for r in range(k):
if col[r] == "A":
cnt_a[r] -= 1
col.insert(0, p)
# add new row contributions of this column
for r in range(k + 1):
if col[r] == "A":
cnt_a[r] += 1
fill[k] += 1
if p == "A":
col_a[c] += 1
# a column's verdict is fixed at the moment it becomes full
if k + 1 == R and col_a[c] in (0, R):
uniform_cols += 1
uc = uniform_cols > 0
ur = any(fill[r] == C and cnt_a[r] in (0, C) for r in range(R))
results.append([True, uc, ur])
return results