Search~30 min2s · 256 MBtarget O((start + count) × n) in the worst case time, O(n) spaceclassic twin: lc-131backtracking
A label printer cuts a product code into segments. The scanner accepts a segment only when it reads the same from left to right and from right to left, like aba. The planner wants to see the ways to cut a code into accepted segments.
A code of 20 identical letters has more than half a million ways, so the planner reads one page of the list. The list is in a fixed order, and the task is to return one page of it.
Write split_page(text, start, count).
text into consecutive pieces that together are the whole text, and every piece reads the same in both directions.|, for example aa|b.count splits starting at position start of the list, counting from 0. Return fewer when the list ends first.Input: text = "aab", start = 0, count = 5
Output: ["a|a|b", "aa|b"]The solution builds a split piece by piece. It tries the piece lengths in rising order and keeps a piece only if it reads the same both ways. The trace lists the choices in the order they are tried.
| Step | Position | Piece tried | What happens |
|---|---|---|---|
| 1 | 0 | a | accepted: continue at position 1 |
| 2 | 1 | a | accepted: continue at position 2 |
| 3 | 2 | b | accepted: the text is used up, so `a |
| 4 | 1 | ab | rejected: it does not read the same both ways |
| 5 | 0 | aa | accepted: continue at position 2 |
| 6 | 2 | b | accepted: the text is used up, so `aa |
| 7 | 0 | aab | rejected |
The list has 2 splits, so the page holds both.
Input: text = "racecar", start = 1, count = 2
Output: ["r|a|cec|a|r", "r|aceca|r"]The full list is r|a|c|e|c|a|r, r|a|cec|a|r, r|aceca|r and racecar. The page starts at position 1 and holds 2 entries.
Input: text = "abca", start = 0, count = 3
Output: ["a|b|c|a"]The piece abca starts and ends with the same letter but does not read the same both ways. Only the single letters are accepted.
1 ≤ text.length ≤ 20, with letters from a to z0 ≤ start ≤ 20,0001 ≤ count ≤ 50A text of 20 identical letters has 2^19 = 524,288 splits. Building the whole list and then reading a page costs about 10 million steps or more. Stopping the search as soon as the page is full needs only the first start + count splits, at most 20,050.