Implement 2048 tilt move
Company: Glean
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to implement array and matrix manipulation, deterministic state-transition logic, and rule-based merging behavior in a grid-based simulation.
Constraints
- The board is always 4x4.
- Each cell is 0 or a power of two (2, 4, 8, ...).
- dir is exactly one of 'up', 'down', 'left', 'right'.
- A tile may merge at most once per move.
- Only the tilt/move logic is required — no random tile spawning and no scoring.
Examples
Input: ([[2,0,2,4],[2,2,2,0],[4,4,4,4],[0,0,0,0]], 'left')
Expected Output: [[4, 4, 0, 0], [4, 2, 0, 0], [8, 8, 0, 0], [0, 0, 0, 0]]
Explanation: Swipe left. Row [2,0,2,4]: the two 2s merge to 4, giving [4,4,0,0]. Row [2,2,2,0]: leftmost pair merges to 4, the third 2 cannot merge again -> [4,2,0,0]. Row [4,4,4,4]: two independent merges -> [8,8,0,0]. Empty row stays empty.
Input: ([[2,0,2,4],[2,2,2,0],[4,4,4,4],[0,0,0,0]], 'right')
Expected Output: [[0, 0, 4, 4], [0, 0, 2, 4], [0, 0, 8, 8], [0, 0, 0, 0]]
Explanation: Swipe right is the mirror of left. Row [2,2,2,0] now merges its rightmost pair, leaving the stray 2 to the left -> [0,0,2,4]. Tiles pack toward the right edge.
Input: ([[2,2,4,0],[2,0,4,0],[0,2,0,8],[2,2,0,8]], 'up')
Expected Output: [[4, 4, 8, 16], [2, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Explanation: Swipe up merges within each column toward row 0. Column 0 [2,2,0,2] -> 2+2 merge then trailing 2 -> [4,2,0,0]. Column 2 [4,4,0,0] -> [8,0,0,0]. Column 3 [0,0,8,8] -> [16,0,0,0].
Input: ([[2,2,4,0],[2,0,4,0],[0,2,0,8],[2,2,0,8]], 'down')
Expected Output: [[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 0, 0], [4, 4, 8, 16]]
Explanation: Swipe down packs and merges columns toward row 3. Column 0 [2,2,0,2] -> bottom pair merges -> [0,0,2,4]. Column 3 [0,0,8,8] -> [0,0,0,16].
Input: ([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], 'left')
Expected Output: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Explanation: Edge case: an all-empty board is unchanged in every direction.
Input: ([[2,2,2,2],[8,8,8,8],[2,4,8,16],[0,2,0,2]], 'right')
Expected Output: [[0, 0, 4, 4], [0, 0, 16, 16], [2, 4, 8, 16], [0, 0, 0, 4]]
Explanation: Swipe right. [2,2,2,2] and [8,8,8,8] each form two independent merges packed right. [2,4,8,16] has no equal neighbors so it only packs (already full). [0,2,0,2] -> the two 2s merge -> [0,0,0,4].
Hints
- Reduce the 2D problem to a 1D one: solve 'slide and merge a single line toward index 0', then apply it to the correct row/column orientation per direction.
- For a single line: first drop the zeros to pack non-zero tiles together, then scan left-to-right merging equal adjacent pairs, advancing past a merged pair so the same tile is never merged twice.
- Handle 'right' by reversing each row, applying the left-slide, then reversing back. Handle 'up'/'down' by transposing to columns (and reversing for 'down').