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.
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 <= 105
1 <= buildings.length <= 105
buildings[i] = [x, y]
1 <= x, y <= n
All coordinates of buildings are unique.
Solutions
Solution 1: Hash Table + Sorting
We can group the buildings by their x-coordinates and y-coordinates, storing them in hash tables \(\text{g1}\) and \(\text{g2}\), respectively. Here, \(\text{g1[x]}\) represents all y-coordinates for buildings with x-coordinate \(x\), and \(\text{g2[y]}\) represents all x-coordinates for buildings with y-coordinate \(y\). Then, we sort these lists.
Next, we iterate through all buildings. For the current building \((x, y)\), we retrieve the corresponding y-coordinate list \(l_1\) from \(\text{g1}\) and the x-coordinate list \(l_2\) from \(\text{g2}\). We check the conditions to determine whether the building is covered. A building is covered if \(l_2[0] < x < l_2[-1]\) and \(l_1[0] < y < l_1[-1]\). If so, we increment the answer by one.
After finishing the iteration, we return the final answer.
The complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\), where \(n\) is the number of buildings.