Leetcode #1840: Maximum Building Height
In this guide, we solve Leetcode #1840 Maximum Building Height 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
You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
Input: n = 5, restrictions = [[2,1],[4,1]]
Output: 2
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.
Python Solution
class Solution:
def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
r = restrictions
r.append([1, 0])
r.sort()
if r[-1][0] != n:
r.append([n, n - 1])
m = len(r)
for i in range(1, m):
r[i][1] = min(r[i][1], r[i - 1][1] + r[i][0] - r[i - 1][0])
for i in range(m - 2, 0, -1):
r[i][1] = min(r[i][1], r[i + 1][1] + r[i + 1][0] - r[i][0])
ans = 0
for i in range(m - 1):
t = (r[i][1] + r[i + 1][1] + r[i + 1][0] - r[i][0]) // 2
ans = max(ans, t)
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.