Festival Train Split

MediumbacktrackingAlso known as Palindrome Partitioning

A heritage railway writes a train as one letter per carriage colour: rbrr is red, blue, red, red. For its summer festival it splits a long train into shorter ones, keeping the carriage order. Each short train must read the same from either end, so that it looks the same whichever way it pulls in. A single carriage always qualifies, and the manager wants to see every possible split.

Your task

Write trainSplits(carriages). Return every way to cut the string carriages into consecutive pieces so that each piece reads the same forwards and backwards. Write each way as the list of pieces from left to right; joined together, they must give back carriages.

The ways can be in any order, each listed once. An empty string has exactly one way, with no pieces: return [[]].

trainSplits(carriages: string) → string[][] Any order of the returned list is accepted.

Examples

Example 1
Input
carriages = "rbrr"
Output
[["r", "b", "r", "r"], ["r", "b", "rr"], ["rbr", "r"]]
Why

Single carriages always work, and so do rr at the end and rbr at the start. The pieces rb, br, brr and rbrr are not symmetric.

Example 2
Input
carriages = "gbbg"
Output
[["g", "b", "b", "g"], ["g", "bb", "g"], ["gbbg"]]
Why

The whole train gbbg is symmetric, so a single piece is a valid plan. The piece bb in the middle is symmetric too, but gb and gbb are not.

Constraints

  • 0 ≤ carriages.length ≤ 12
  • carriages contains only lowercase letters.
  • Ways may be returned in any order, but the pieces inside a way stay in train order.
Start with brute force

Between each pair of neighbouring carriages you either cut or do not cut, which gives 2n − 1 patterns. You can try them all and keep those where every piece is symmetric. For 12 carriages that is 2,048 patterns, which is fine, but each extra carriage doubles the count. For rgbyw, where all colours are different, only one pattern works, yet the brute force builds all 16. Checking the first piece before going further cuts away every pattern that starts badly in one go.

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