Sliding Tile Board: Merge Logic for All Four Directions
Arrays & HashingModel answerLast updated
Implement the slide-and-merge move for a 2048-style grid in all four directions, sharing a single merge routine across every direction.
Sliding Tile Board: Merge Logic for All Four Directions
You are building the core move engine for a sliding-tile puzzle played on an n × n grid of integers. Each cell holds either a positive integer (a tile) or 0 (an empty cell). A player move chooses a direction and the board responds by sliding every tile as far as possible toward that side, then merging tiles that collide.
Move Rules
- Tiles slide until they hit a wall or another tile; all gaps close.
- Two adjacent tiles with equal values merge into one tile whose value is their sum, placed at the leading position.
- A tile produced by a merge is frozen for the rest of that move — it cannot merge again.
- When three or more equal tiles are lined up, the pair closest to the wall the tiles are sliding toward merges first.
Left move examples (one row shown):
[2, 2, 2, 0] → [4, 2, 0, 0] (first pair merges; third tile slides)
[2, 0, 2, 4] → [4, 4, 0, 0] (gap closes, equal pair merges)
[4, 4, 4, 4] → [8, 8, 0, 0] (two independent merges)
[2, 4, 8, 16] → [2, 4, 8, 16] (nothing to merge or slide)
The same rules apply to right, up, and down — only the direction toward which tiles collapse changes.
Clarifying Questions to Consider
Before coding, think through these points (you do not need to ask them, but your solution should reflect the answers):
- The board is always square;
ncan be any positive integer. - A move should return a new board and a boolean indicating whether anything changed. Do not modify the input in place.
- Spawning a new random tile after a move and tracking the score are out of scope for this exercise.
Part 1 — Move Left
Implement move_left(board). It must:
- Accept a 2-D list of integers and return
(new_board, changed). - Apply the slide-and-merge rules to every row independently.
- Pass a test suite you write and run before continuing to Part 2.
Your tests should cover at minimum:
- A row with a gap between equal tiles
- Three equal tiles in a row
- Four equal tiles in a row
- A fully packed row with no merges possible
- A row that is already solved (all tiles at the left, no adjacent duplicates)
- An empty row
Part 2 — All Four Directions
Extend your solution to move(board, direction) where direction is one of "left", "right", "up", or "down".
Constraint: the merge routine from Part 1 must be reused as-is. Do not write a separate merge function for each direction.
Two design approaches are worth knowing:
- Rotation: transform the board so every move becomes a left move, then transform back.
- Index remapping: leave the board in place and iterate rows or columns in the order the chosen direction dictates.
Implement one approach. Be ready to explain the trade-offs between the two: which is easier to read, which is more likely to produce an off-by-one indexing error, and what the computational cost difference is.
Add tests for right, up, and down. For each direction, include at least one case where a merge happens and one where nothing changes.
Hints
Hint 1
Start by writing a function that processes a single list (one row or one column), not the whole board. Once that is correct, applying it to the full grid is straightforward.
Hint 2
For the single-line merge: strip the zeros out first, then make a single left-to-right pass merging adjacent equal values, then pad with zeros at the right. This keeps the logic simple and avoids fiddly index arithmetic.
Hint 3
For multi-direction support, the rotation approach lets you reuse move_left directly: rotating the board 90° clockwise turns a 'up' move into a 'left' move. Map each direction to a number of clockwise rotations, apply them, call move_left, then rotate back the same amount in the opposite direction.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Single-row merge, then the full board
The cleanest way to handle one row is a three-step pipeline:
- Compact: remove all zeros to get only the live tiles, in order.
- Merge: walk left-to-right through the compacted list; when two neighboring values are equal, replace the left one with their sum and mark the right one for removal (set to zero). Skip over a freshly merged tile so it cannot merge again.
- Pad: append zeros until the list is back to its original length.
This is O(n) in the row length and avoids any tricky in-place shifting.
def merge_line_left(line: list[int]) -> tuple[list[int], bool]:
"""Slide and merge one row/column toward the left (index 0)."""
original = line[:]
n = len(line)
# Step 1: compact — drop zeros
tiles = [x for x in line if x != 0]
# Step 2: merge adjacent equal pairs, left-to-right
i = 0
while i < len(tiles) - 1:
if tiles[i] == tiles[i + 1]:
tiles[i] *= 2
del tiles[i + 1] # remove the consumed tile
i += 1 # either way, the tile at i is now frozen
# Step 3: pad with zeros on the right
result = tiles + [0] * (n - len(tiles))
return result, result != original
def move_left(board: list[list[int]]) -> tuple[list[list[int]], bool]:
new_board = []
changed = False
for row in board:
new_row, row_changed = merge_line_left(row)
new_board.append(new_row)
changed = changed or row_changed
return new_board, changed
Test cases to verify before continuing:
assert merge_line_left([2, 0, 2, 4])[0] == [4, 4, 0, 0] # gap closes, then merge
assert merge_line_left([2, 2, 2, 0])[0] == [4, 2, 0, 0] # three equal: first pair merges
assert merge_line_left([4, 4, 4, 4])[0] == [8, 8, 0, 0] # four equal: two merges
assert merge_line_left([2, 4, 8, 16])[0] == [2, 4, 8, 16] # nothing changes
assert merge_line_left([0, 0, 0, 0])[0] == [0, 0, 0, 0] # empty row
assert merge_line_left([4, 2, 0, 0])[0] == [4, 2, 0, 0] # already solved, no change
assert merge_line_left([2, 2, 2, 0])[1] == True # changed flag
assert merge_line_left([4, 2, 0, 0])[1] == False # unchanged flag
Part 2 — All four directions via rotation
The key insight: rotating the board maps any direction onto left.
| Direction | Clockwise rotations before | Clockwise rotations after |
|---|---|---|
| left | 0 | 0 |
| down | 1 | 3 |
| right | 2 | 2 |
| up | 3 | 1 |
numpy.rot90 rotates counter-clockwise by default, so passing k=-1 or k=3 gives one clockwise step.
import numpy as np
def rotate_cw(board: list[list[int]], k: int) -> list[list[int]]:
"""Rotate board clockwise k times."""
arr = np.array(board)
rotated = np.rot90(arr, k=-k) # rot90 default is CCW; negate for CW
return rotated.tolist()
ROTATIONS = {"left": 0, "down": 1, "right": 2, "up": 3}
def move(board: list[list[int]], direction: str) -> tuple[list[list[int]], bool]:
k = ROTATIONS[direction]
rotated = rotate_cw(board, k)
merged, changed = move_left(rotated)
result = rotate_cw(merged, -k % 4) # rotate back
return result, changed
If you want to avoid the numpy dependency, a pure-Python clockwise rotation is:
def rotate_cw_pure(board):
n = len(board)
return [[board[n - 1 - c][r] for c in range(n)] for r in range(n)]
Rotation vs. Index Remapping
Rotation
- The merge logic stays exactly as written for
move_left. No special-casing per direction. - Easier to read and audit — the transformation is separate from the merge.
- The rotation itself is O(n²), which is the same order as the merge pass. No asymptotic cost difference.
- One risk: getting the rotation count or the inverse rotation wrong. A quick unit test per direction catches this immediately.
Index remapping
- No copies of the board are made for rotation; you iterate directly over the relevant rows or columns in the right order.
- In practice the constant-factor gain is negligible for n ≤ 10, which covers all real game boards.
- Reading and columns in reverse requires careful index arithmetic, which is a common source of off-by-one bugs. The logic is harder to follow at a glance.
For a game board (n ≤ 10), rotation is almost always the better engineering choice: simpler code, lower bug risk, identical asymptotic cost.
Common Mistakes
- Double merge: allowing a freshly merged tile to merge again in the same pass. The
i += 1after every iteration, combined with deleting the consumed tile, prevents this — do not add ani += 1inside theifbranch. - Mutating the input: always work on a copy; returning the original list modified in place makes the
changedflag unreliable. - Off-by-one in rotation inverse: rotating clockwise 1 time to prepare means rotating clockwise 3 times (not -1 times) to restore — use
(-k) % 4. - Column direction confusion: when reasoning about
upanddownwithout rotation, it is easy to swap which end merges first. The rotation approach eliminates this class of bug entirely.
Overall complexity: O(n²) time, O(n²) space for the new board. Both are optimal since every cell must be visited at least once.