Postcard Mountain Skylines

MediumbacktrackingAlso known as Generate Parentheses

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

For a fixed number of up-strokes, the designer wants one postcard per 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 in 6 ways, but only 2 stay above the horizon. For example, UDDU dips below on its third stroke and DUUD on its first. Both valid skylines reach at most height 2.

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, taller than the card allows.

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

With no strokes there is still one postcard, the flat horizon, which is the empty string.

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 and keep those that stay between the horizon and the limit and end on the horizon. For climbs = 8 that is 65,536 strings to keep at most 1,430, and the waste grows with n.

Most rejected strings are already invalid after a stroke or two, and the strings starting with D alone are half of all strings. Checking only at the end means building each one 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