Palindromes
medium 22 minA palindrome reads the same forwards and backwards.
See it run
Watch two pointers check a string, centres grow palindromes outwards, and interval tables fill from short ranges to the whole string.
Operations
Check: two pointers
Is the whole string a palindrome? Put L at the first letter and R at the last, compare, and walk both inwards until they meet or a pair differs.
Step 1 of 7
Pointers at both ends
- r0L
- a1
- c2
- e3
- c4
- a5
- r6R
L starts at index 0 and R at index n - 1 = 6. A palindrome must match its outer pair first.
Step 1: Pointers at both ends
def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False # outer pair differs left += 1 # pair matched: move both inwards right -= 1 return True # pointers met: every pair matched- Time
- O(n)
- Space
- O(1)
- comparisons
- floor(n / 2)
- s == s[::-1]
- O(n) extra space
Say the invariant: everything outside [L, R] already matches its mirror, so only the inside is left to check.
In the real world
The same palindromes doing real jobs. Pick one and step through it.
abba has no palindrome longer than one letter centred on a letter. The whole word sits on the gap between the two b's.
Step 1 of 3
Odd centres fail
- a0L
- b1
- b2R
- a3
Centre 1 (b) compares a and b; centre 2 (b) compares b and a. Both stop at once, so odd centres only ever find single letters here.
Step 1: Odd centres fail
print(longest_palindrome("abba"), longest_palindrome("cbbd")) # abba bbCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Forgetting even-length centres
criticalExpanding only from letters finds odd-length palindromes. Every even-length palindrome (bb, abba) is centred on a gap, so abba returns a single letter.
Wrongfor c in range(len(s)): l, r = expand(c, c) # odd only ...Rightfor c in range(len(s)): for l, r in (expand(c, c), expand(c, c + 1)): # odd and even ...Returning the overshot range
criticalThe expand loop stops only after a failed comparison or going out of bounds, so L and R are each one step past the palindrome. Slicing s[l:r + 1] includes the two letters that did not match (or wraps with a negative index).
Wrongwhile l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1return s[l:r + 1] # includes the mismatched endsRightwhile l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1return s[l + 1:r] # strictly between the overshot pointersFilling is_pal from the top row down
criticalCell (i, j) reads is_pal[i + 1][j − 1], the row below. Looping i from 0 upwards reads a row that is still all False, so long palindromes are missed.
Wrongfor i in range(n): for j in range(i, n): is_pal[i][j] = s[i] == s[j] and (j - i < 2 or is_pal[i + 1][j - 1])Rightfor i in range(n - 1, -1, -1): # bottom row first for j in range(i, n): is_pal[i][j] = s[i] == s[j] and (j - i < 2 or is_pal[i + 1][j - 1])Using the subsequence DP for a substring question
majorLongest palindromic substring and subsequence are different problems. The LPS table skips letters, so on bbbab it returns 4 (bbbb), while the longest contiguous palindrome is only 3 (bbb).
Wrongdef longest_palindromic_substring_len(s): return longest_palindrome_subseq(s) # bbbab -> 4: wrongRightdef longest_palindromic_substring_len(s): return len(longest_palindrome(s)) # bbbab -> 3Applying the reverse trick to substrings
majorLPS = LCS(s, reverse(s)) works for subsequences. The longest common substring of s and its reverse is not always a palindrome: for abacdfgdcaba it is abacd.
Wrongbest = longest_common_substring(s, s[::-1]) # may not be a palindromeRightbest = longest_palindrome(s) # expand around centresComparing raw text in Valid Palindrome
minor"A man, a plan, a canal: Panama" is a palindrome only after ignoring case, spaces and punctuation. Comparing the raw characters returns False.
Wrongreturn s == s[::-1]Rightwhile l < r: if not s[l].isalnum(): l += 1; continue if not s[r].isalnum(): r -= 1; continue if s[l].lower() != s[r].lower(): return False l, r = l + 1, r - 1return True
Interview tips
How to explain it
- A palindrome is matching ends around a smaller palindrome, so the inner answer can be reused.
- Expand around all 2n − 1 centres: O(n²) time, O(1) space. Mention the is_pal table and Manacher's O(n).
- For subsequences: match adds 2, mismatch takes the max of dropping either end; it equals LCS with the reverse.
Spot it in problems
- Longest, count or all palindromic substrings: expand around centres.
- Fewest insertions or deletions to make a palindrome: n − LPS.
- Cut into palindromic pieces: is_pal table plus a 1D cuts DP, or backtracking to list them.
Memory tricks
- EXO: Expand from each centre, eXtend while matching, Optimal O(1) space.
- Odd on a letter, even in a gap.
- The loop overshoots by one: return s[L + 1 : R].
Watch out
- Substring is contiguous, subsequence is not: bbbab gives 3 and 4.
- Fill is_pal by length or with i descending.
- Ties: return any longest palindrome unless the problem says which.