Leetcode 2768: Number of Black Blocks

grid47
grid47
Exploring patterns and algorithms
Feb 4, 2024 6 min read

Given an m x n grid with some black cells specified by a coordinates list, determine how many 2x2 blocks contain exactly 0, 1, 2, 3, or 4 black cells.
Problem
Approach
Steps
Complexity
Input: The input consists of integers m, n, and a 2D integer array coordinates.
Example: Input: m = 4, n = 4, coordinates = [[1, 1]]
Constraints:
• 2 <= m, n <= 10^5
• 0 <= coordinates.length <= 10^4
• 0 <= coordinates[i][0] < m
• 0 <= coordinates[i][1] < n
• Each coordinate pair is distinct.
Output: Return a list of size 5 where the i-th entry is the number of blocks containing exactly i black cells.
Example: Output: [9, 3, 0, 0, 0] for m = 4, n = 4, coordinates = [[1, 1]].
Constraints:
• Output should be a list of integers of size 5.
Goal: To efficiently count the number of blocks containing exactly i black cells for i = 0 to 4.
Steps:
• Use a hash map to count how many black cells each block contains.
• Iterate through each black cell and update the counts for all blocks it contributes to.
• Aggregate the counts to produce the final output array.
Goal: Ensure the solution works for large inputs and handles sparse grids efficiently.
Steps:
• 2 <= m, n <= 10^5
• 0 <= coordinates.length <= 10^4
• Each coordinate pair is distinct.
Assumptions:
• Coordinates are pairwise distinct.
• Blocks outside the bounds of the grid do not exist.
Input: Input: m = 4, n = 4, coordinates = [[1, 1]]
Explanation: There are 9 blocks with 0 black cells and 3 blocks with 1 black cell. Blocks with >1 black cell do not exist.

Input: Input: m = 3, n = 3, coordinates = [[0, 0], [1, 1], [0, 2]]
Explanation: 2 blocks have 1 black cell, 2 blocks have 2 black cells, and no blocks have 0, 3, or 4 black cells.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus