Chat app~30 min2s · 256 MBtarget O(n²) time, O(n²) spaceclassic twin: lc-132dp
A chat app stores a reaction code, a string of lowercase letters. To compress it, the app cuts the code into pieces so that every piece reads the same forwards and backwards.
A single letter is such a piece. Your team lead asks: "What is the fewest number of cuts that makes every piece read the same in both directions?"
Write fewest_cuts(code).
code is a non-empty string of lowercase letters.Input: code = "abbaxcdc"
Output: 2The work has two parts. First, find which ranges [i, j] are palindromes. A range is one when its end letters match and the range inside is also one, so we fill by length.
Then let cuts[j] be the fewest cuts for the first j + 1 letters. If the whole prefix is a palindrome it needs 0. Otherwise try every start i of the last piece, when code[i..j] is a palindrome, and use cuts[i - 1] + 1.
| Length | Palindromic ranges |
|---|---|
| 1 | all 8 single letters |
| 2 | bb (positions 1 to 2) |
| 3 | cdc (positions 5 to 7) |
| 4 | abba (positions 0 to 3) |
| 5 to 8 | none |
j |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
cuts[j] |
0 | 1 | 1 | 0 | 1 | 2 | 3 | 2 |
The last value is 2: cut abbaxcdc into abba, x and cdc.
Input: code = "level"
Output: 0The whole code reads the same both ways.
Input: code = "aaba"
Output: 1Cut once into a and aba. Taking the longest palindrome from the start, aa, would need 2 cuts.
1 ≤ len(code) ≤ 1,000, with lowercase letters a to z.len(code) - 1, one cut between every pair of letters.A string of n letters has 2 to the power of n - 1 ways to be cut, so none can be listed. Two tables of about n²/2 entries are small: 500,500 each for n = 1,000. A cubic cost would be 10^9 and too slow, so each entry must take a constant time.