Great question again! You're seeing a real-world example of how tiny implementation changes in Python can affect performance—even if the logic is the same. Let's walk through what's going on between your two versions of the isPalindrome function.
📌 The two versions:
1. Slower version (7 ms) – string concatenation inside a loop:
letters = ''
for letter in s.lower():
if letter.isalnum():
letters += letter # += on strings = new string every time
2. Faster version (5 ms) – list comprehension + str.join:
letters = ''.join([letter for letter in s.lower() if letter.isalnum()])
⚙️ Why is the second one faster?
✅ String concatenation in a loop (+= in version 1) is inefficient:
- Strings in Python are immutable.
- Every time you do
letters += letter, Python creates a new string in memory:
- Copies the existing string
letters
- Adds the new
letter
- Assigns that new string back to
letters
- This is O(n²) in the worst case for n letters!
(Because each step copies everything so far.)
🚀 ''.join([...]) with list comprehension is much faster:
- The list comprehension builds a list of filtered characters efficiently in memory.
''.join(...) then builds the final string in one allocation.
- This approach is effectively O(n) because we build the string just once.
🔍 Real-world impact
You're only seeing 2 ms difference in speed (7 ms → 5 ms), and that's for a likely small-ish input (like a LeetCode test case). For large strings, that difference could be much more pronounced.
✅ TL;DR:
| Version | Approach | Performance |
|---|
letters += letter | Inefficient string concat in loop (O(n²)) | Slower |
''.join([...]) | List + single join operation (O(n)) | Faster |
🔁 A small optimization tip:
You can make the second version slightly cleaner and more performant by using a generator expression instead of a list comprehension:
letters = ''.join(letter for letter in s.lower() if letter.isalnum())
- This avoids creating a whole list in memory, using a generator instead.
- Same time complexity and often even faster/lightweight.
So your answer:
The second version is faster because building strings with ''.join() is much more efficient than concatenating repeatedly in a loop. 👏✨
Let me know if you want to benchmark them with timeit too!