Valid Palindrome [Python Algorithm]
Third post in the series. This one is less about choosing a data structure and more about a distinction I’d been getting wrong all evening: which string methods change the original, and which ones hand you a new one.
Problem
Given a string, return true if it reads the same forward and backward. Comparison is case-insensitive and ignores anything that isn't a letter or a digit.
"Was it a car or a cat I saw?" -> true
"tab a cat" -> falseThe first example becomes "wasitacaroracatisaw" once you strip the spaces, the question mark, and the capitals. That reads the same in both directions.
The second becomes "tabacat", which does not. Reversed it's "tacabat".
The Two Halves
The problem looks fiddly until you notice it’s two independent steps that happen to sit in the same function.
- Clean the string. Keep letters and digits, drop everything else, lowercase what’s left.
- Compare it to its reverse.
Step 2 is one line once step 1 is done. Almost all of the work, and all of my mistakes, were in step 1.
Solution
def is_palindrome(s):
cleaned = ""
for char in s:
if char.isalnum():
cleaned += char.lower()
return cleaned == cleaned[::-1]Three pieces of syntax carry this.
char.isalnum() asks whether a character is alphanumeric, which is exactly the filter the problem describes. Letters and digits return True; spaces, punctuation, and symbols return False.
char.lower() returns the lowercase version, which is what makes the comparison case-insensitive.
cleaned[::-1] reverses the string. It's slice syntax with a step of -1, meaning "walk through this from the end to the start."
Get Daniel (Heedong) Jang’s stories in your inbox
Join Medium for free to get updates from this writer.
Tracing "Wa?":
char="W" isalnum -> True cleaned = "w"
char="a" isalnum -> True cleaned = "wa"
char="?" isalnum -> False skipped, cleaned = "wa"Then "wa" == "aw" is False.
Complexity
Time: O(n). One pass to build the cleaned string, one to reverse it, one to compare.
Space: O(n). The cleaned string is a second copy of the input.
Doing It Without Extra Space
The version above is the one to write first, but interviewers often follow up with “can you do it in O(1) space?” You can, by walking two pointers inward from both ends instead of building a new string.
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return TrueThe inner while loops skip over anything that isn't alphanumeric, so the pointers only ever compare real characters. Still O(n) time, but no second string, so O(1) space.
It’s harder to write correctly under pressure, and the left < right guard inside the skip loops is easy to forget. Without it, a string of only punctuation runs one pointer past the other. I'd lead with the first solution and mention this one as the follow-up.
Pitfalls
Using the whole string where I meant one character. My first attempt:
for char in s:
if s.isalnum(): # checking the entire string
cleaned += char.lower()s is the full input; char is the single character this iteration is looking at. "Was it a car or a cat I saw?".isalnum() is False, because the string contains spaces. So the condition never passed, the body never ran, and cleaned stayed empty on every input.
What makes this one worth writing down is that it produced no error. The code ran, returned True for everything (an empty string equals its own reverse), and looked plausible. I made this exact mistake three times in a row before it stuck.
Calling .lower() and throwing the result away. This line does nothing:
char.lower().lower() returns a new lowercase string. It does not modify char. If nothing catches the return value, the new string is discarded and the original is untouched.
char = "W"
char.lower()
print(char) # "W", unchanged
char = char.lower()
print(char) # "w"This is the distinction I actually took away from the problem. Some methods return a new value and leave the original alone; others modify in place and return nothing.
"ABC".lower() # returns "abc"
sorted([3, 1, 2]) # returns [1, 2, 3]
" hi ".strip() # returns "hi"
nums.append(4) # modifies nums, returns None
nums.sort() # modifies nums, returns NoneStrings are immutable in Python, so every string method falls in the first group. There is no such thing as a string method that edits in place. Lists give you both kinds, which is where the confusion starts: sorted(nums) and nums.sort() do the same job with opposite mechanics.
The rule of thumb: if a method returns something, you have to use it. If it returns None, it already did the work.

![How Harris Finds Corners [Computer Vision]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*ItXucl5GOsTBAUt-PSl3Gg.jpeg)
![Why Derivative Filters Break on Noisy Images [Computer Vision]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*lFtJlmZU-iHSTX42XSFDWA.jpeg)
![Vectors [ML Math]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*vGvmn2pRRohfpstlxImeog.jpeg)
![Group Anagrams [Python Algorithm]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*8q0JsR9cIgqk0YaKtpbRJA.jpeg)



