Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2282. Number of People That Can Be Seen in a Grid

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, and down.
  • 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.

: :

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.