Red and black tile slides and jumps
I was asked this
No reports yet. Sign in to say where you were asked it.
A strip of cells holds red tiles (R), black tiles (B) and empty cells (_). The board is a string such as "RR_B_B".
Movement rules
- A red tile only moves right. A black tile only moves left.
- Slide: a tile moves one cell in its direction into an empty cell.
- Jump: a tile moves two cells in its direction, over exactly one tile of the other color, into an empty cell. The jumped tile is not removed. A tile can never jump a tile of its own color.
- One tile moves per move. Tiles never leave the board.
Part 1. Implement valid_moves(board: str) -> list[tuple[int, int]]. Return every legal move as (from_index, to_index), ordered by from_index (a tile with both a slide and a jump lists the slide first).
Part 2. Implement min_moves(start: str, target: str) -> int. Return the fewest moves that turn start into target, or -1 if it cannot be done. Be ready to return the move sequence too.
Constraints: 0 <= len(board) <= 20; both boards have the same length and use only R, B and _.
Example 1
valid_moves("R_B") -> [(0, 1), (2, 1)]
valid_moves("RB_") -> [(0, 2)] # red jumps black; black is blocked
valid_moves("RR_") -> [(1, 2)] # a red cannot jump a red
Example 2
min_moves("R_B", "B_R") -> 3
R_B -> _RB (red slides 0 -> 1)
_RB -> BR_ (black jumps 2 -> 0)
BR_ -> B_R (red slides 1 -> 2)
min_moves("RB", "BR") -> -1 # no tile can move at all
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.
