Count Covered Buildings Problem
Description
LeetCode Problem 3531.
You are given a positive integer n, representing an n x n city. You are also given a 2D grid buildings, where buildings[i] = [x, y] denotes a unique building located at coordinates [x, y].
A building is covered if there is at least one building in all four directions: left, right, above, and below.
Return the number of covered buildings.
Example 1:

Input: n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]
Output: 1
Explanation:
- Only building [2,2] is covered as it has at least one building:
- above ([1,2])
- below ([3,2])
- left ([2,1])
- right ([2,3])
- Thus, the count of covered buildings is 1.
Example 2:

Input: n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]
Output: 0
Explanation:
- No building has at least one building in all four directions.
Example 3:

Input: n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]
Output: 1
Explanation:
- Only building [3,3] is covered as it has at least one building:
- above ([1,3])
- below ([5,3])
- left ([3,2])
- right ([3,5])
- Thus, the count of covered buildings is 1.
Constraints:
2 <= n <= 10^51 <= buildings.length <= 10^5buildings[i] = [x, y]1 <= x, y <= n- All coordinates of
buildingsare unique.
Solution
Approach: Hash Table + Sorting
Group the buildings by row and by column: for every x, keep the sorted list of y values, and for every y, the sorted list of x values. A building (x, y) has neighbors on all four sides exactly when x lies strictly between the smallest and largest x in its column group and y lies strictly between the smallest and largest y in its row group. Count the buildings that satisfy both conditions.
Complexity: O(n log n) time and O(n) extra space, where n is the number of buildings.
from collections import defaultdict
class Solution:
def countCoveredBuildings(self, n: int, buildings: List[List[int]]) -> int:
g1 = defaultdict(list)
g2 = defaultdict(list)
for x, y in buildings:
g1[x].append(y)
g2[y].append(x)
for x in g1:
g1[x].sort()
for y in g2:
g2[y].sort()
ans = 0
for x, y in buildings:
l1 = g1[x]
l2 = g2[y]
if l2[0] < x < l2[-1] and l1[0] < y < l1[-1]:
ans += 1
return ans