DVCQ-P2

The skyline

Practice 2 of 6Divide and conquer12 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No buildingsNot run
3One buildingNot run
4Touching, same heightNot run
5Touching, different heightsNot run
6One inside anotherNot run
7Same left edgeNot run
8Same right edgeNot run
9A hidden buildingNot run
10Not in orderNot run
1150,000 scattered buildingsNot run
1250,000 nested buildingsNot run