#3531

Count Covered Buildings

Medium
ArrayHash TableSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Group buildings by their coordinates and check for coverage efficiently using sets.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two dictionaries to group buildings by their x and y coordinates.
  2. 2Step 2: For each building, check if it has buildings in all four directions using the dictionaries.
  3. 3Step 3: Count and return the number of covered buildings.
solution.py10 lines
1def countCoveredBuildings(n, buildings):
2    x_map, y_map = {}, {}
3    for x, y in buildings:
4        x_map.setdefault(x, []).append(y)
5        y_map.setdefault(y, []).append(x)
6    count = 0
7    for x, y in buildings:
8        if len(x_map[x]) > 1 and len(y_map[y]) > 1:
9            count += 1
10    return count

Complexity note: We only traverse the buildings a couple of times, leading to linear time complexity.

  • 1Buildings must have neighbors in all four directions to be counted.
  • 2Grouping by coordinates allows efficient checking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.