Ride-hailing app~35 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-214string-algorithms
A ride app prints each booking reference as a code of capital letters and digits. A label printer supports a design where a code reads the same from both ends.
Your team lead asks: "A code may be a palindrome after we add letters at the front, at the back, or at both ends. What is the fewest letters to add?" The added letters can be any symbols.
Write fewest_additions(code).
code is the booking reference.code already reads the same both ways.Input: code = "7QA9AQ"
Output: 1The suffix QA9AQ is a palindrome, so adding a single 7 at the back gives 7QA9AQ7. The table tests each length from the top, as a prefix and as a suffix, until one is a palindrome.
| Length | Prefix | Palindrome? | Suffix | Palindrome? |
|---|---|---|---|---|
| 6 | 7QA9AQ | no | 7QA9AQ | no |
| 5 | 7QA9A | no | QA9AQ | yes |
Input: code = "4GRE"
Output: 3No prefix or suffix longer than one symbol is a palindrome, so the best is to keep one symbol and add the mirror of the other 3.
Input: code = "KAYAK3"
Output: 1The prefix KAYAK is a palindrome, so adding a single 3 at the front gives 3KAYAK3.
1 ≤ len(code) ≤ 200,000code uses only the capital letters A to Z and the digits 0 to 9.Testing each prefix and suffix length letter by letter costs up to about 5,000,000,000 steps. A long prefix can almost be a palindrome and fail near its middle. Matching the code against its own reverse with a table of borders finds the longest palindromic prefix and suffix in about 800,002 steps.