Shortest Palindrome
HardStringskmp
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given a string s, you may only add characters to its front. Return the shortest palindrome that can be formed this way.
The result is unique: it is s with the fewest possible characters prepended. If s is empty, return the empty string.
Aim for O(n) time, for example with the KMP failure function.
Examples
Input: s = "aacecaaa"
Output: "aaacecaaa"
The longest palindromic prefix is "aacecaa"; prepend the reverse of the remaining "a".
Input: s = "abcd"
Output: "dcbabcd"
Only "a" is a palindromic prefix, so prepend "dcb".
Constraints
- 0 <= s.length <= 5 * 10^4
- `s` consists of lowercase English letters only
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.