#2768

Number of Black Blocks

Medium
ArrayHash TableEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking every block, we can use a HashSet to track the black cells and count the blocks based on their contributions to neighboring blocks. This reduces unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a HashSet to store the black cell coordinates.
  2. 2Step 2: For each black cell, determine which 2x2 blocks it contributes to.
  3. 3Step 3: For each block, count the number of black cells it contains based on the black cells that contribute to it.
  4. 4Step 4: Update the count array for blocks with 0 to 4 black cells.
solution.py15 lines
1# Full working Python code
2
3def countBlackBlocks(m, n, coordinates):
4    black_cells = set(map(tuple, coordinates))
5    count = [0] * 5
6    for x, y in black_cells:
7        for dx in range(2):
8            for dy in range(2):
9                block_x, block_y = x - dx, y - dy
10                if 0 <= block_x < m - 1 and 0 <= block_y < n - 1:
11                    black_count = sum((block_x + i, block_y + j) in black_cells for i in range(2) for j in range(2))
12                    count[black_count] += 1
13    count[0] = (m - 1) * (n - 1) - sum(count)  # Calculate blocks with 0 black cells
14    return count
15

Complexity note: The time complexity is O(n) because we only iterate over the black cells and their contributions to blocks. The space complexity is O(n) due to storing the black cells in a HashSet.

  • 1Using a HashSet allows for quick lookups of black cells.
  • 2Counting contributions from black cells reduces unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.