Question presented to candidate: "Given a string, return the longest substring that is a palindrome. For example, babad gives bab or aba, and cbbd gives bb. Please write it in Python, and tell me the time and space cost."
What a strong answer should cover:
- Every palindrome has a centre: n character centres and n - 1 gap centres; expand two pointers outward from each while the characters match.
- Track the best (start, length) and slice once at the end; O(n^2) time, O(1) extra space.
- The O(n^3) brute force and the O(n^2)-space DP as alternatives; Manacher as the O(n) follow-up.
- Edge cases: empty string, single character, even-length palindromes, ties.
- Python specifics: slicing (
s[a:b]) copies, so do not slice inside the loop;[[False] * n] * naliases one row n times; Python loops are slow enough that the O(n^3) brute force is unusable beyond a few hundred characters.
Clarifying questions expected:
- "Substring or subsequence?"
- "If there is a tie, which palindrome should I return?"
Code / implementation expected: Yes โ longest_palindrome(s) in Python using expand-around-centre with index pointers.