Postcard Mountain Skylines

MediumbacktrackingAlso known as Generate Parentheses

A designer draws simple mountain skylines for a set of postcards. The pen moves left to right in equal strokes, and each stroke goes either up a slope (U) or down one (D). A skyline starts on the horizon, ends on the horizon, and never dips below it, because the land cannot go underground. The card is short, so no point may rise more than maxHeight strokes above the horizon.

For a series with a fixed number of up-strokes, the designer wants one postcard for every skyline that fits. UUDD is one tall peak; UDUD is two small hills.

Your task

Write allSkylines(climbs, maxHeight). Return every string made of climbs letters U and climbs letters D where, reading left to right, the height (number of Us so far minus number of Ds so far) never drops below 0 and never goes above maxHeight.

Return the strings in any order, each exactly once. If no skyline fits, return an empty list. For climbs = 0 the only skyline is the flat horizon, the empty string, so return [""].

allSkylines(climbs: int, maxHeight: int) → string[] Any order of the returned list is accepted.

Examples

Example 1
Input
climbs = 2
maxHeight = 2
Output
["UUDD", "UDUD"]
Why

Two Us and two Ds can be arranged 6 ways, but only 2 stay above the horizon. UDDU goes below after its third stroke, and DUUD goes below on its first. Both survivors reach at most height 2, so they fit.

Example 2
Input
climbs = 3
maxHeight = 2
Output
["UUDUDD", "UUDDUD", "UDUUDD", "UDUDUD"]
Why

Without a height limit there would be 5 skylines. The fifth, UUUDDD, climbs to height 3, which is taller than the card allows.

Example 3
Input
climbs = 0
maxHeight = 0
Output
[""]
Why

No strokes at all. There is still one postcard, showing a flat horizon, so the answer has one empty string in it.

Constraints

  • 0 ≤ climbs ≤ 8
  • 0 ≤ maxHeight ≤ 8
  • Strings may be returned in any order.
Start with brute force

Generate all 22n strings of U and D, then keep the ones that stay between the horizon and the height limit and end on the horizon. For climbs = 8 that is 65,536 strings checked to keep at most 1,430, and the share of waste keeps growing with n.

Most rejected strings were doomed after a stroke or two: the ones starting with D alone are half of all strings. Checking at the end means building every one of them in full first.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code