Magicsheet logo

Number of Black Blocks

Medium
97.8%
Updated 6/1/2025

Number of Black Blocks

What is this problem about?

The Number of Black Blocks problem gives you an m×n grid (initially all white) and a list of black cell coordinates. A "block" is a 2×2 subgrid. For each number k from 0 to 4, count how many 2×2 blocks contain exactly k black cells. This Number of Black Blocks coding problem uses hash map enumeration over cell contributions to 2×2 blocks.

Why is this asked in interviews?

Uber, Twitter, Visa, Stripe, Roblox, Block, and Capital One ask this to test the ability to enumerate which 2×2 blocks are affected by each black cell and aggregate counts efficiently — without iterating over all m×n possible blocks. The array, hash table, and enumeration interview pattern is directly applied.

Algorithmic pattern used

Enumerate affected blocks per black cell. Each black cell (r, c) belongs to up to four 2×2 blocks: their top-left corners can be at (r-1,c-1), (r-1,c), (r,c-1), (r,c). For each valid corner (within grid bounds), increment blockCount[corner] in a hash map. After processing all black cells, the hash map values give the number of black cells in each 2×2 block. Count blocks by their value to fill result[0..4]. Blocks not in the hash map (value=0) are counted as (m-1)*(n-1) - len(blockCount).

Example explanation

Grid 4×4. Black cells: (0,0), (1,1), (0,1).

  • (0,0) affects blocks with top-left: valid only (0,0) (within 4×4). blockCount[(0,0)] += 1.
  • (1,1) affects (0,0), (0,1), (1,0), (1,1). blockCount[(0,0)]+=1 → 2, (0,1)+=1, (1,0)+=1, (1,1)+=1.
  • (0,1) affects (0,0)+=1→3, (0,1)+=1→2. blockCount: {(0,0):3, (0,1):2, (1,0):1, (1,1):1}. result[3]=1, result[2]=1, result[1]=2. result[0] = 9-4=5.

Common mistakes candidates make

  • Iterating all (m-1)*(n-1) blocks directly (too slow for large m, n).
  • Not clipping block corners to valid grid boundaries.
  • Not computing result[0] as total blocks minus blocks in the hash map.
  • Off-by-one in the number of valid 2×2 blocks: (m-1)*(n-1) total.

Interview preparation tip

"How many k-cell sub-grids exist?" problems are solved by inverting the perspective: instead of scanning each sub-grid, for each colored cell, enumerate which sub-grids it belongs to (at most 4 for a 2×2 block). This flip in perspective reduces O(m*n) scanning to O(B) where B is the number of black cells. Practice this "enumerate contributions" pattern for 2D problems — it appears in "number of rectangles," "count sub-matrices," and "block coloring" problems across interviews at Stripe, Uber, and Block.

Similar Questions