Number of Black Blocks - Problem
You are given two integers m and n representing the dimensions of a 0-indexed m x n grid.
You are also given a 0-indexed 2D integer matrix coordinates, where coordinates[i] = [x, y] indicates that the cell with coordinates [x, y] is colored black. All cells in the grid that do not appear in coordinates are white.
A block is defined as a 2 x 2 submatrix of the grid. More formally, a block with cell [x, y] as its top-left corner where 0 <= x < m - 1 and 0 <= y < n - 1 contains the coordinates [x, y], [x + 1, y], [x, y + 1], and [x + 1, y + 1].
Return a 0-indexed integer array arr of size 5 such that arr[i] is the number of blocks that contains exactly i black cells.
Input & Output
Example 1 — Basic 3x3 Grid
$
Input:
m = 3, n = 3, coordinates = [[0,0],[1,1]]
›
Output:
[1,3,0,0,0]
💡 Note:
There are 4 possible 2x2 blocks. Block (0,0) contains cells [(0,0),(0,1),(1,0),(1,1)] with 2 black cells. Block (0,1) contains 1 black cell at (1,1). Block (1,0) contains 1 black cell at (1,1). Block (1,1) contains 0 black cells. So we have 1 block with 0 black, 3 blocks with 1 black, and 0 blocks with 2+ black.
Example 2 — All Black 2x2
$
Input:
m = 2, n = 2, coordinates = [[0,0],[0,1],[1,0],[1,1]]
›
Output:
[0,0,0,0,1]
💡 Note:
Only one 2x2 block possible at (0,0) containing all 4 black cells [(0,0),(0,1),(1,0),(1,1)], so result is [0,0,0,0,1].
Example 3 — No Black Cells
$
Input:
m = 2, n = 2, coordinates = []
›
Output:
[1,0,0,0,0]
💡 Note:
Only one 2x2 block with no black cells, so result is [1,0,0,0,0].
Constraints
- 1 ≤ m, n ≤ 105
- 0 ≤ coordinates.length ≤ 104
- coordinates[i].length == 2
- 0 ≤ xi < m
- 0 ≤ yi < n
- It is guaranteed that coordinates contains pairwise distinct coordinates.
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
3x3 grid with black cells at (0,0) and (1,1)
2
Find All Blocks
Identify all possible 2x2 blocks and count black cells
3
Count by Density
Group blocks by number of black cells: [1,3,0,0,0]
Key Takeaway
🎯 Key Insight: Use hash set for O(1) coordinate lookup when checking each 2x2 block's black cells
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code