LeetCode 2282: Number of People That Can Be Seen in a Grid Solution
Master LeetCode problem 2282 (Number of People That Can Be Seen in a Grid), 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.
2282. Number of People That Can Be Seen in a Grid
Problem Explanation
Explanation:
To solve this problem, we can iterate through the grid and for each cell, check if it can see any other person. A person in a cell can see another person if there are no obstacles in a straight line along the row or column. We can maintain four arrays to store the maximum indices of people seen in each direction for each cell. By iterating through the grid and updating these arrays, we can count the total number of people that can be seen.
- Initialize four arrays to store the maximum indices of people seen in each direction:
left,right,up, anddown. - Iterate through the grid and update the above arrays for each cell.
- For each cell, count the number of people that can be seen based on the maximum indices stored in the arrays.
Time Complexity: O(NM), where N is the number of rows and M is the number of columns in the grid. Space Complexity: O(NM) for storing the maximum indices arrays.
: :
Solution Code
class Solution {
public int numPeopleSeen(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int[] left = new int[m];
int[] right = new int[m];
int[] up = new int[n];
int[] down = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
int maxRight = -1;
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
left[j] = Math.max(left[j], i);
right[j] = Math.max(right[j], maxRight);
count++;
} else {
maxRight = j;
}
}
}
for (int j = 0; j < m; j++) {
int maxDown = -1;
for (int i = 0; i < n; i++) {
if (grid[i][j] == 1) {
up[i] = Math.max(up[i], j);
down[i] = Math.max(down[i], maxDown);
} else {
maxDown = i;
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2282 (Number of People That Can Be Seen in a Grid)?
This page provides optimized solutions for LeetCode problem 2282 (Number of People That Can Be Seen in a Grid) 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 2282 (Number of People That Can Be Seen in a Grid)?
The time complexity for LeetCode 2282 (Number of People That Can Be Seen in a Grid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2282 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2282 in Java, C++, or Python.