← Questions

Drop a Tetris piece and clear full rows

0

Implement a single step of a Tetris-like game.

You get three inputs:

  • background: an H x W grid of 0/1. 1 is an occupied cell, 0 is empty. Row 0 is the top.
  • block: an h x w grid of 0/1 that describes the falling piece. A 1 is part of the piece. A 0 is empty space inside the piece's bounding box and never collides with anything.
  • offset: the zero-indexed board column where the piece's left edge (column 0 of block) is aligned.

The piece starts completely above the board and falls straight down. It does not move sideways or rotate. It stops at the last position where none of its filled cells overlaps an occupied cell or goes below the bottom row.

Implement:

def drop_block(background: list[list[int]], block: list[list[int]], offset: int) -> list[list[int]] | None

When the piece stops:

  1. Lock it into the board (its filled cells become 1).
  2. Remove every row that is now completely full. Rows above a removed row move down; empty rows are added at the top so the board keeps its size.
  3. Return the new board. Do not modify the input.

If the piece comes to rest with any filled cell still above row 0, it does not fit: return None.

Constraints: 1 <= H, W <= 1000, 1 <= h, w <= 10, 0 <= offset <= W - w, and block has at least one 1.

Example 1

background = [[0,0,0],
              [0,0,0],
              [0,1,0],
              [1,1,0]]
block  = [[1,1],
          [0,1]]
offset = 1

The piece's left column stops on the 1 at row 2, so its top row lands on row 1 and its lower cell on row 2. Row 2 becomes [0,1,1], not full. Result:

[[0,0,0],
 [0,1,1],
 [0,1,1],
 [1,1,0]]

Example 2

background = [[0,0,0],
              [0,0,0],
              [1,0,1]]
block  = [[1,1,1],
          [0,1,0]]
offset = 0

The stem drops into the gap. Rows 1 and 2 both become full and are removed. Result: [[0,0,0],[0,0,0],[0,0,0]].

Start with a correct simulation, then make the landing step faster than moving the piece one row at a time.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding