Perform matrix Candy Crush elimination
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: This question evaluates a candidate's competency in matrix and grid manipulation, neighborhood/adjacency checks, and simulation of state transitions in an array-based board.
Constraints
- 1 <= m, n (the matrix may also be empty, in which case return it unchanged)
- 0 <= matrix[i][j], where 0 denotes an empty cell
- Removals are decided simultaneously from the original matrix (mark first, then clear).
- Only ONE round of elimination is performed; do not cascade.
- Within each column, surviving cells keep their top-to-bottom relative order after gravity.
Examples
Input: ([[1, 1, 1], [1, 2, 2], [3, 4, 5]],)
Expected Output: [[0, 0, 1], [1, 2, 2], [3, 4, 5]]
Explanation: (0,0) [right+down] and (0,1) [left+right] each have two same-color (1) neighbors and are removed; (0,2) and (1,0) have only one, so they survive. Gravity leaves the columns unchanged (empties already on top).
Input: ([[1, 2, 3], [4, 5, 6], [7, 8, 9]],)
Expected Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Explanation: All cells are distinct colors, so no cell has even one same-color neighbor; nothing is removed and the matrix is returned unchanged.
Hints
- Compute all removals first into a separate boolean grid, scanning the ORIGINAL matrix; only after the full scan should you zero out the marked cells. Mutating in place mid-scan changes a neighbor's color and corrupts later decisions.
- A cell qualifies for removal when it has >= 2 (not exactly 2) orthogonal neighbors of the same non-zero color.
- For gravity, process each column independently: collect its non-zero values top-to-bottom, then write them back at the BOTTOM of the column and fill the top with zeros.