Leetcode #2015: Average Height of Buildings in Each Segment
In this guide, we solve Leetcode #2015 Average Height of Buildings in Each Segment in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
A perfectly straight street is represented by a number line. The street has building(s) on it and is represented by a 2D integer array buildings, where buildings[i] = [starti, endi, heighti].
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Greedy, Array, Sorting, Heap (Priority Queue)
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: buildings = [[1,4,2],[3,9,4]]
Output: [[1,3,2],[3,4,3],[4,9,4]]
Explanation:
From 1 to 3, there is only the first building with an average height of 2 / 1 = 2.
From 3 to 4, both the first and the second building are there with an average height of (2+4) / 2 = 3.
From 4 to 9, there is only the second building with an average height of 4 / 1 = 4.
Python Solution
class Solution:
def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]:
cnt = defaultdict(int)
d = defaultdict(int)
for start, end, height in buildings:
cnt[start] += 1
cnt[end] -= 1
d[start] += height
d[end] -= height
s = m = 0
last = -1
ans = []
for k, v in sorted(d.items()):
if m:
avg = s // m
if ans and ans[-1][2] == avg and ans[-1][1] == last:
ans[-1][1] = k
else:
ans.append([last, k, avg])
s += v
m += cnt[k]
last = k
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.