Festival Train Split

MediumbacktrackingAlso known as Palindrome Partitioning

A heritage railway paints each carriage a single colour and writes a train as one letter per carriage: rbrr is red, blue, red, red. For its summer festival the railway splits one long train into shorter trains, keeping the carriages in their order.

The station manager has one rule: every short train must look the same whichever way it pulls into the platform, so its colours must read the same from either end. A single carriage always qualifies. The manager wants to see every possible way to split the train.

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. rr at the end reads the same both ways, and so does rbr at the start. rb, br, brr and the whole rbrr do not, so no plan can use them.

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

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

Constraints

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

Between each pair of neighbouring carriages you either cut or you do not, so there are 2n − 1 cut patterns. Try them all and keep the ones where every piece is symmetric. For 12 carriages that is 2,048 patterns, which is fine, but each extra carriage doubles it: 30 carriages would mean over 500 million.

For a train like rgbyw with all colours different, only one pattern works, yet the brute force still builds all 16. Checking the first piece before going further cuts away every pattern that starts with a bad piece 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