The problem
Seen from far away, a row of buildings makes one outline against the sky. Each building is a rectangle standing on the ground, given as (left, right, height): it covers the x values from left up to, but not including, right. Return the outline as a list of key points (x, h): at x the outline’s height changes to h. Between buildings the height is 0.
skyline([(2, 9, 10), (3, 7, 15), (5, 12, 12),
(15, 20, 10), (19, 24, 8)])
# [(2, 10), (3, 15), (7, 12), (12, 0),
# (15, 10), (20, 8), (24, 0)]
- The points are sorted by x, and there is exactly one point for each x where the height changes.
- Two neighbouring points never have the same height: if the height does not change at some x, there is no point there.
- The last point has height 0. No buildings give
[].
Points may be tuples or lists. All numbers are whole numbers, left < right, and every height is at least 1.
Limits
- Up to 50,000 buildings, in any order. Aim for O(n log n): divide and conquer, as lesson 2’s first worked example describes.
Builds on DVCQ-1 The pattern and DVCQ-2 The master theorem in practice.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | No buildings | Not run | |
| 3 | One building | Not run | |
| 4 | Touching, same height | Not run | |
| 5 | Touching, different heights | Not run | |
| 6 | One inside another | Not run | |
| 7 | Same left edge | Not run | |
| 8 | Same right edge | Not run | |
| 9 | A hidden building | Not run | |
| 10 | Not in order | Not run | |
| 11 | 50,000 scattered buildings | Not run | |
| 12 | 50,000 nested buildings | Not run |