Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2768: Number of Black Blocks

In this guide, we solve Leetcode #2768 Number of Black Blocks in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Hash Table, Enumeration

Intuition

Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.

By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.

Approach

Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.

This keeps the solution linear while remaining easy to explain in an interview setting.

Steps:

  • Initialize a hash map for seen items or counts.
  • Iterate through the input, querying/updating the map.
  • Return the first valid result or the final computed value.

Example

Input: m = 3, n = 3, coordinates = [[0,0]] Output: [3,1,0,0,0] Explanation: The grid looks like this: There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0].

Python Solution

class Solution: def countBlackBlocks( self, m: int, n: int, coordinates: List[List[int]] ) -> List[int]: cnt = Counter() for x, y in coordinates: for a, b in pairwise((0, 0, -1, -1, 0)): i, j = x + a, y + b if 0 <= i < m - 1 and 0 <= j < n - 1: cnt[(i, j)] += 1 ans = [0] * 5 for x in cnt.values(): ans[x] += 1 ans[0] = (m - 1) * (n - 1) - len(cnt.values()) return ans

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy