Update a Neuron Grid
Company: Scale AI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates competency in matrix/grid manipulation, neighbor-counting logic for eight-directional adjacency, simultaneous state transitions, and space-optimized in-place updates (O(1) auxiliary space).
Constraints
- 1 <= m, n <= 300 (matrix may also be empty)
- 0 <= neurons[i][j] (values are non-negative integers)
- A firing neuron has value 0; a non-firing neuron has value > 0
- All updates are computed simultaneously from the original state
- A cell's value can never go below 0
Examples
Input: ([[0, 0, 0], [0, 0, 0], [0, 0, 0]],)
Expected Output: [[6, 0, 6], [0, 0, 0], [6, 0, 6]]
Explanation: All cells firing. Each corner has exactly 3 firing neighbors -> becomes 6. Edge cells have 5 firing neighbors and the center has 8, neither equals 3, so they stay 0.
Input: ([[5]],)
Expected Output: [[3]]
Explanation: A single non-firing cell with 0 firing neighbors (0 or 1) -> decrement by 2: 5 - 2 = 3.
Input: ([[1]],)
Expected Output: [[0]]
Explanation: Single non-firing cell, 0 firing neighbors -> decrement by 2 gives -1, clamped to 0.
Input: ([[0, 0], [0, 0]],)
Expected Output: [[6, 6], [6, 6]]
Explanation: Every cell is firing and each has exactly 3 firing neighbors -> all become 6.
Input: ([[5, 0, 5], [0, 0, 0], [5, 0, 5]],)
Expected Output: [[5, 6, 5], [6, 0, 6], [5, 6, 5]]
Explanation: Each corner (5) has exactly 3 firing neighbors -> not <=1 and not >3, so it keeps its value. Each edge 0 has exactly 3 firing neighbors -> becomes 6. The center 0 has 4 firing neighbors (not 3) -> stays 0.
Input: ([],)
Expected Output: []
Explanation: Empty matrix returns unchanged.
Input: ([[2, 0, 0], [0, 0, 0], [0, 0, 2]],)
Expected Output: [[2, 0, 6], [0, 0, 0], [6, 0, 2]]
Explanation: Cell (0,0)=2 has 3 firing neighbors -> keeps value 2. Cell (0,2)=0 has exactly 3 firing neighbors -> becomes 6 (likewise (2,0)). The four interior 0 cells each have more than 3 firing neighbors so they stay 0; cell (2,2)=2 also has 3 firing neighbors and keeps its value.
Hints
- Snapshot the original matrix (deep copy) so neighbor counts are computed from the pre-update state, not from values you have already changed.
- A neighbor is 'firing' only if its ORIGINAL value is 0. Check all 8 directions and stay within bounds.
- Apply exactly one rule per cell: firing cells only change (to 6) when the firing-neighbor count is exactly 3; a count of exactly 3 on a non-firing cell falls through to 'keep value'.
- For the O(1) follow-up, encode both old and new state in each cell (e.g. store new_value * K + old_value for a large K), count neighbors using value % K, then divide out in a second pass.