Number of Black Blocks — LeetCode 2768 Python Solution
- Problem
- #2768
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- m = 3, n = 3, coordinates = [[0,0]]
- Output
- [3,1,0,0,0]
- Explanation
- The grid looks like this:
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2768. Number of Black Blocks is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2768. Number of Black Blocks?
- LeetCode 2768. Number of Black Blocks is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2768. Number of Black Blocks?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2768. Number of Black Blocks?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2768. Number of Black Blocks cover?
- LeetCode 2768. Number of Black Blocks is tagged Array, Hash Table and Enumeration on LeetCode.