Skip to content

3531. Count Covered Buildings 👍

  • Time: $O(|\texttt{buildings}|)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  int countCoveredBuildings(int n, vector<vector<int>>& buildings) {
    int ans = 0;
    vector<int> northernmost(n + 1, INT_MAX);
    vector<int> southernmost(n + 1, 0);
    vector<int> westernmost(n + 1, INT_MAX);
    vector<int> easternmost(n + 1, 0);

    for (const vector<int>& building : buildings) {
      const int x = building[0];
      const int y = building[1];
      northernmost[x] = min(northernmost[x], y);
      southernmost[x] = max(southernmost[x], y);
      westernmost[y] = min(westernmost[y], x);
      easternmost[y] = max(easternmost[y], x);
    }

    for (const vector<int>& building : buildings) {
      const int x = building[0];
      const int y = building[1];
      if (northernmost[x] < y && y < southernmost[x]  //
          && westernmost[y] < x && x < easternmost[y])
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
  public int countCoveredBuildings(int n, int[][] buildings) {
    int ans = 0;
    int[] northernmost = new int[n + 1];
    int[] southernmost = new int[n + 1];
    int[] westernmost = new int[n + 1];
    int[] easternmost = new int[n + 1];
    Arrays.fill(northernmost, Integer.MAX_VALUE);
    Arrays.fill(southernmost, 0);
    Arrays.fill(westernmost, Integer.MAX_VALUE);
    Arrays.fill(easternmost, 0);

    for (int[] building : buildings) {
      final int x = building[0];
      final int y = building[1];
      northernmost[x] = Math.min(northernmost[x], y);
      southernmost[x] = Math.max(southernmost[x], y);
      westernmost[y] = Math.min(westernmost[y], x);
      easternmost[y] = Math.max(easternmost[y], x);
    }

    for (int[] building : buildings) {
      final int x = building[0];
      final int y = building[1];
      if (northernmost[x] < y && y < southernmost[x] //
          && westernmost[y] < x && x < easternmost[y])
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def countCoveredBuildings(self, n: int, buildings: list[list[int]]) -> int:
    northernmost = [math.inf] * (n + 1)
    southernmost = [0] * (n + 1)
    westernmost = [math.inf] * (n + 1)
    easternmost = [0] * (n + 1)

    for x, y in buildings:
      northernmost[x] = min(northernmost[x], y)
      southernmost[x] = max(southernmost[x], y)
      westernmost[y] = min(westernmost[y], x)
      easternmost[y] = max(easternmost[y], x)

    return sum(northernmost[x] < y < southernmost[x]
               and westernmost[y] < x < easternmost[y]
               for x, y in buildings)