Drop a Tetris piece and clear full rows
I was asked this
No reports yet. Sign in to say where you were asked it.
Implement a single step of a Tetris-like game.
You get three inputs:
-
background: anH x Wgrid of0/1.1is an occupied cell,0is empty. Row 0 is the top. -
block: anh x wgrid of0/1that describes the falling piece. A1is part of the piece. A0is 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 ofblock) 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:
- Lock it into the board (its filled cells become
1). - 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.
- 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
