LeetCode 2768: Number of Black Blocks Solution
Master LeetCode problem 2768 (Number of Black Blocks), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2768. Number of Black Blocks
Problem Explanation
Explanation:
To solve this problem, we can iterate through the given coordinates and mark the black cells on the grid. Then, we can count the number of blocks that contain exactly i black cells by iterating through each 2x2 submatrix of the grid.
- Initialize a 2D grid of size m x n, initially all cells are white.
- Iterate through the given coordinates and mark the black cells on the grid.
- Count the number of blocks that contain exactly i black cells by iterating through each 2x2 submatrix of the grid and counting the black cells in each block.
- Return an array arr of size 5 where arr[i] represents the number of blocks that contain exactly i black cells.
Time Complexity: O(m * n + coordinates.length)
Space Complexity: O(m * n)
Solution Code
class Solution {
public int[] countBlackBlocks(int m, int n, int[][] coordinates) {
int[][] grid = new int[m][n];
for (int[] coord : coordinates) {
grid[coord[0]][coord[1]] = 1;
}
int[] arr = new int[5];
for (int i = 0; i < m - 1; i++) {
for (int j = 0; j < n - 1; j++) {
int blackCount = grid[i][j] + grid[i+1][j] + grid[i][j+1] + grid[i+1][j+1];
arr[blackCount]++;
}
}
return arr;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2768 (Number of Black Blocks)?
This page provides optimized solutions for LeetCode problem 2768 (Number of Black Blocks) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2768 (Number of Black Blocks)?
The time complexity for LeetCode 2768 (Number of Black Blocks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2768 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2768 in Java, C++, or Python.