Connect Four board with gravity drops and board snapshots
I was asked this
No reports yet. Sign in to say where you were asked it.
Build the board for a gravity-based four-in-a-row game. Players drop single-character colored pieces into columns. A piece falls straight down and stops in the lowest empty cell of its column.
Implement ConnectFourBoard:
-
ConnectFourBoard(rows, cols)creates an empty board withrowsrows andcolscolumns. Every cell starts as the character'0'. Row0is the top row, and rowrows - 1is the bottom. -
drop(color, col) -> List[List[str]]drops a piece ofcolorinto columncol, then returns the board after the move as a 2D list of characters.-
coloris any single character other than'0', for example'R','Y'or'G'. - If column
colis already full, the board does not change, and you still return its current state. - The returned grid must be an independent copy. Changes the caller makes to it must not affect the board, and later drops must not change a grid returned earlier.
- Raise an error if
colis outside0..cols-1.
-
Part 2. Add last_move_wins() -> bool. It returns true when the piece placed by the most recent successful drop forms a line of at least 4 pieces of its color: horizontal, vertical or diagonal. It returns false if the last drop hit a full column.
Constraints. 1 <= rows, cols <= 100. There are at most 10^4 calls to drop.
Example 1
b = ConnectFourBoard(3, 3)
b.drop('G', 2) -> [['0','0','0'],
['0','0','0'],
['0','0','G']]
b.drop('B', 2) -> [['0','0','0'],
['0','0','B'],
['0','0','G']]
Example 2
b = ConnectFourBoard(2, 2)
b.drop('G', 0)
b.drop('B', 0)
b.drop('G', 0) -> [['B','0'],
['G','0']] # column 0 is full, so nothing changes
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.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
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.
