Count Covered Buildings - Problem
šļø City Planning Challenge: Count Covered Buildings
Imagine you're a city planner analyzing building coverage in a grid-based city layout. You have an n Ć n city grid with various buildings scattered throughout. Your task is to identify which buildings are "covered" - meaning they have protection from all four cardinal directions.
A building at coordinates [x, y] is considered covered if there exists at least one building in each of the four directions:
- 𔸠Left: At least one building with same y-coordinate but smaller x-coordinate
- 𔺠Right: At least one building with same y-coordinate but larger x-coordinate
- 𔹠Above: At least one building with same x-coordinate but smaller y-coordinate
- š”» Below: At least one building with same x-coordinate but larger y-coordinate
Goal: Return the total count of covered buildings in the city.
Input & Output
example_1.py ā Small City Grid
$
Input:
n = 5, buildings = [[1,1],[2,2],[3,2],[2,3],[3,3],[4,3]]
āŗ
Output:
1
š” Note:
Only building at (3,2) is covered. It has building (2,2) to its left, (4,3) area doesn't provide right coverage. Actually, let me recalculate: (3,2) has (2,2) left, no building directly right in row 2, so it's not covered. Building (2,3) has (2,2) above, (3,2) doesn't share row... The building at (3,3) has (2,3) left, no right, (3,2) above, no below in column 3 below row 3. Only (2,3) could be covered: left=(1,1)? No, different row. Actually (2,2) is covered: left=none in row 2, right=(3,2) in row 2, up=none in col 2, down=(2,3) in col 2. So not covered. Let me re-examine: (3,2) has left=(2,2), right=none, up=none, down=(3,3). Not fully covered.
example_2.py ā Cross Pattern
$
Input:
n = 4, buildings = [[2,1],[1,2],[2,2],[3,2],[2,3]]
āŗ
Output:
1
š” Note:
Building at (2,2) is covered because it has (1,2) to the left, (3,2) to the right, (2,1) above, and (2,3) below. It's the center of a cross pattern.
example_3.py ā No Coverage
$
Input:
n = 3, buildings = [[1,1],[3,3]]
āŗ
Output:
0
š” Note:
Neither building has coverage in all four directions since they don't share rows or columns with other buildings.
Constraints
- 1 ⤠n ⤠1000
- 1 ⤠buildings.length ⤠n2
- buildings[i].length == 2
- 1 ⤠buildings[i][0], buildings[i][1] ⤠n
- All buildings have unique coordinates
Visualization
Tap to expand
Understanding the Visualization
1
Map the City
Create hash maps grouping buildings by rows and columns
2
Check Coverage
For each building, verify neighbors exist in all four directions
3
Count Approved
Sum up buildings that have complete directional coverage
Key Takeaway
šÆ Key Insight: Group buildings by coordinates to transform O(n²) pairwise comparisons into efficient O(1) directional lookups!
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code