Valid Palindrome
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Ignoring spaces, punctuation and upper/lower case, check whether the text reads the same forwards and backwards.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Which two characters must match first?
- Hint 2What should you do when one of them is not a letter or digit?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Two friends stand at the two ends of a bridge holding the same word written on a long banner. They both look at the letter in front of them. Same? Each takes a step towards the middle. Different? It is not a palindrome. If they meet in the middle with every pair matching, it is one. A comma or space in front of someone? He just steps over it.
- The obvious way
Build a cleaned copy, reverse it and compare. Works, but needs a whole extra copy of the text.
- The key insight
A palindrome is mirror-symmetric, so the outermost pair must match, then the next pair in, and so on. Two walkers, one at each end, stepping inward and skipping anything that is not a letter or digit, check this with no extra copy.
- The algorithm
- Put one pointer at the very start and one at the very end.
- Move the left one right until it points at a letter or digit; move the right one left likewise.
- Compare the two letters ignoring case. Different? Answer False.
- Step both inward and repeat. When they meet, answer True.
Watch it run
Exampletext = "Ab,bA" (letters and one comma)
Left looks at A, right looks at A. They match (case ignored). Step inward.
matched pairs: A-A
Where people slip
- Keep left < right inside the skip loops, or the walkers can cross on a text full of punctuation.
- An empty or all-punctuation text counts as a palindrome (True).
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def is_palindrome(text):
left, right = 0, len(text) - 1
while left < right:
while left < right and not text[left].isalnum():
left += 1 # step over commas, spaces...
while left < right and not text[right].isalnum():
right -= 1
if text[left].lower() != text[right].lower():
return False
left += 1
right -= 1
return TrueNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.