Uber OA Coding Interview: Count 2×2 Submatrices by Number of Black Cells

16 Views
No Comments

For a grid of black and white cells with rows rows and cols columns, you’re given an array black that contains the [row, column] coordinates of all the black cells in the grid.

Your task is to compute how many 2 x 2 submatrices of the grid contain exactly blackCount black cells, for each 0 <= blackCount <= 4. As a result, you will return an array of 5 integers, where the i-th element is the number of 2 x 2 submatrices with exactly i black cells.

It is guaranteed that black cell coordinates in the black array are pairwise unique, so the same cell is not colored twice.

Example

For rows = 3, cols = 3, and black = [[0, 0], [0, 1], [1, 0]], the output should be solution(rows, cols, black) = [1, 2, 0, 1, 0].

The key idea is to count only the 2×2 submatrices that can be affected by black cells. Each black cell belongs to at most four 2×2 submatrices, so we gather all candidate top-left positions in a set to avoid duplicates, then count how many black cells each candidate contains and increment the corresponding bucket from 0 to 4. This hash-set based local counting approach is simple and efficient.

END
 0