Festival Train Split
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
carriages = "rbrr"
[["r", "b", "r", "r"], ["r", "b", "rr"], ["rbr", "r"]]
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.
carriages = "gbbg"
[["g", "b", "b", "g"], ["g", "bb", "g"], ["gbbg"]]
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- Hint 1
In
rbrr, the first short train starts at the first carriage. Check which ofr,rb,rbrandrbrrread the same from both ends. - Hint 2
After a symmetric first train, the remaining carriages are the same puzzle, only shorter. Every plan is a symmetric first train followed by a plan for the rest.
- Hint 3
Write
cut(start): for every end fromstarton, if the piece fromstarttoendis symmetric, add it to the plan and callcut(end + 1). Whenstartreaches the end of the string, the plan is complete. - Hint 4
Check a piece with two pointers walking in from both ends. Push the piece before the recursive call, pop it after, and record a copy of each complete plan. Skipping a non-symmetric piece skips every plan that starts with it.
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.
How to solve it
The solution chooses a symmetric first train and then solves the rest of the string the same way. A piece that is not symmetric is rejected before anything is built on it.
The trace below uses rbrr.
- With
ras the first train, the rest isbrr. The piecebworks, and thenrrcan be split as[r, r]or kept as[rr], so the search records[r, b, r, r]and[r, b, rr]. The piecesbrandbrrare not symmetric. - The first train
rbis not symmetric, so the search skips it and every plan that would start with it. - The first train
rbris symmetric. The rest isr, so the search records[rbr, r]. - The first train
rbrris not symmetric, so the search is finished.
A common mistake is to use a greedy rule such as always taking the longest symmetric piece. That finds one plan, but the task asks for all of them.
function trainSplits(carriages) {
const plans = [];
const pieces = [];
function symmetric(lo, hi) { // carriages[lo..hi] reads the same both ways?
while (lo < hi) {
if (carriages[lo] !== carriages[hi]) return false;
lo++;
hi--;
}
return true;
}
function cut(start) {
if (start === carriages.length) {
plans.push([...pieces]); // every carriage is placed
return;
}
for (let end = start; end < carriages.length; end++) {
if (!symmetric(start, end)) continue; // only symmetric trains
pieces.push(carriages.slice(start, end + 1));
cut(end + 1);
pieces.pop();
}
}
cut(0);
return plans;
}def train_splits(carriages):
plans = []
pieces = []
def symmetric(lo, hi): # carriages[lo..hi] reads the same both ways?
while lo < hi:
if carriages[lo] != carriages[hi]:
return False
lo += 1
hi -= 1
return True
def cut(start):
if start == len(carriages):
plans.append(pieces[:]) # every carriage is placed
return
for end in range(start, len(carriages)):
if symmetric(start, end): # only symmetric trains are allowed
pieces.append(carriages[start:end + 1])
cut(end + 1)
pieces.pop()
cut(0)
return plansRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.