Mirror Word Splits
Medium · Backtracking · about 20 min
A word game asks you to cut a lowercase word into pieces so that every piece is a palindrome (it reads the same forwards and backwards, like "noon", "eve" or "e"). Return every way to cut s.
- Write each way as its pieces joined by
"|", for example"n|oo|n". Keep the pieces in their original order. - Return the list sorted with the normal string sort (
sorted()in Python,.sort()in JavaScript). Both put"|"after every letter, so"aa|b"comes before"a|a|b". shas 1 to 12 lowercase letters.
mirror_splits("noon") → ["noon", "n|oo|n", "n|o|o|n"]
Hints
- Use a helper that knows where the next piece starts and which pieces are already chosen.
- Try every possible end for the next piece, including the very end of the word. Keep only pieces that equal their own reverse.
- When the next piece would start at the end of the word, join the chosen pieces and record them. Sort everything at the end.
Learn the pattern first: the Backtracking lesson.
More Backtracking problems
- Every Snack Bundle (Easy)
- Every Seating Plan (Easy)
- Keypad Spellings (Easy)
- Distinct Gift Bags (Medium)
- Exact Change Stacks (Medium)
- Trace a Word on the Letter Board (Medium)
- Peaceful Queens Count (Hard)