- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 50 lines of Python from the credited upstream file 218.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def getSkyline(self, buildings: list[list[int]]) -> list[list[int]]:3 n = len(buildings)4 if n == 0:5 return []6 if n == 1:7 left, right, height = buildings[0]8 return [[left, height], [right, 0]]9 10 left = self.getSkyline(buildings[:n 2])11 right = self.getSkyline(buildings[n 2:])12 return self._merge(left, right)13 14 def _merge(self, left: list[list[int]],15 right: list[list[int]]) -> list[list[int]]:16 ans = []17 i = 0 18 j = 0 19 leftY = 020 rightY = 021 22 while i < len(left) and j < len(right):23 24 if left[i][0] < right[j][0]:25 leftY = left[i][1] 26 self._addPoint(ans, left[i][0], max(left[i][1], rightY))27 i += 128 else:29 rightY = right[j][1] 30 self._addPoint(ans, right[j][0], max(right[j][1], leftY))31 j += 132 33 while i < len(left):34 self._addPoint(ans, left[i][0], left[i][1])35 i += 136 37 while j < len(right):38 self._addPoint(ans, right[j][0], right[j][1])39 j += 140 41 return ans42 43 def _addPoint(self, ans: list[list[int]], x: int, y: int) -> None:44 if ans and ans[-1][0] == x:45 ans[-1][1] = y46 return47 if ans and ans[-1][1] == y:48 return49 ans.append([x, y])50