Detect runs and collapse a numeric grid
Company: Roblox
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in 2D array manipulation, pattern detection for contiguous runs, and state simulation involving removal and gravity-like collapse of elements.
Part 1: Detect horizontal and vertical runs
Constraints
- 0 <= m, n <= 500
- If the grid is non-empty, all rows have the same length n
- 0 <= grid[r][c] <= 9
Examples
Input: ([[1,1,1,2],[3,4,4,4],[5,5,5,5]],)
Expected Output: [[0,0,3,0],[1,1,3,0],[2,0,4,0]]
Explanation: There are three horizontal maximal runs of length at least 3, and no vertical runs.
Input: ([[7,7,7],[7,1,2],[7,3,4]],)
Expected Output: [[0,0,3,0],[0,0,3,1]]
Explanation: The top row forms a horizontal run of 7s, and the left column forms a vertical run of 7s.
Hints
- Scan each row once and each column once, counting the length of the current streak of equal values.
- Only add a run when a streak ends; that naturally gives you maximal runs and their starting positions.
Part 2: Remove run cells, apply gravity, and fill with 0
Constraints
- 0 <= m, n <= 500
- If the grid is non-empty, all rows have the same length n
- 0 <= grid[r][c] <= 9
- Perform exactly one detect-remove-collapse pass; do not repeat after gravity
Examples
Input: ([[1,1,1,2],[3,1,4,2],[5,1,4,2],[6,7,8,9]],)
Expected Output: [[0,0,0,0],[3,0,4,0],[5,0,4,0],[6,7,8,9]]
Explanation: Row 0 has a horizontal run of three 1s. Column 1 has a vertical run of three 1s, and column 3 has a vertical run of three 2s. Remove all marked cells simultaneously, then let each column fall.
Input: ([[1,1,1],[1,5,6],[1,8,9]],)
Expected Output: [[0,0,0],[0,5,6],[0,8,9]]
Explanation: The top row is a horizontal run of three 1s, and the first column is also a vertical run of three 1s. After removal, only 5, 6, 8, and 9 remain and fall to the bottom of their columns.
Hints
- Do not modify the grid while you are still detecting runs. First mark every cell that should be removed.
- After marking, rebuild each column from bottom to top by copying only the cells that survive.