Count Covered Buildings - Problem

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.

Input & Output

Example 1 — Grid with One Covered Building
$ Input: n = 4, buildings = [[2,2],[1,2],[3,2],[2,1],[2,3]]
Output: 1
💡 Note: Building at (2,2) is covered: left (2,1), right (2,3), above (1,2), below (3,2). All other buildings lack coverage in at least one direction.
Example 2 — No Covered Buildings
$ Input: n = 3, buildings = [[1,1],[1,2],[2,1]]
Output: 0
💡 Note: No building has coverage in all four directions. Each building is missing at least one directional neighbor.
Example 3 — Multiple Covered Buildings
$ Input: n = 5, buildings = [[2,2],[2,3],[1,2],[3,2],[2,1],[2,4],[1,3],[3,3]]
Output: 2
💡 Note: Buildings (2,2) and (2,3) are both covered, each having neighbors in all four cardinal directions.

Constraints

  • 1 ≤ n ≤ 103
  • 1 ≤ buildings.length ≤ 5 × 102
  • buildings[i] = [xi, yi]
  • 1 ≤ xi, yi ≤ n
  • All buildings are at unique locations

Visualization

Tap to expand
Count Covered Buildings INPUT n = 4 (4x4 grid) 1 2 3 4 1 2 3 4 1,2 2,1 2,2 2,3 3,2 buildings array: [[2,2], [1,2], [3,2], [2,1], [2,3]] = Check if covered = Building ALGORITHM STEPS 1 Build Hash Sets Store all building coords in row/col hash sets 2 For Each Building Check 4 directions: left, right, above, below 3 Check Coverage Building at [2,2]: Left: [1,2] exists? OK Right: [3,2] exists? OK Above: [2,1] exists? OK Below: [2,3] exists? OK 4 Count Covered All 4 directions OK --> increment count row_set: {1,2,3} col_set: {1,2,3} FINAL RESULT Covered Building Found OK OUTPUT 1 Only building [2,2] is covered in all 4 directions Others lack neighbors in 1+ direction Key Insight: Hash Set Optimization Instead of checking all buildings for each direction (O(n^2)), use hash sets to store buildings by row and column. For each building at [x,y], check if there exists a building with smaller x, larger x, smaller y, and larger y in O(1) time per direction. Total time complexity: O(n). TutorialsPoint - Count Covered Buildings | Hash Set Optimization Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
23.4K Views
Medium Frequency
~18 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen