Great question! Both your solutions do the same thing logically, but the difference in speed comes down to how Python handles string concatenation and list comprehensions internally.
Your two solutions:
1. Using += in a loop (7 ms)
letters = ''
for letter in s.lower():
if letter.isalnum():
letters += letter
return letters == letters[::-1]
2. Using list comprehension + join (5 ms)
letters = ''.join([letter for letter in s.lower() if letter.isalnum()])
return letters == letters[::-1]
Why is the second one faster?
1. String concatenation with += is slow
- Strings in Python are immutable.
- Every time you do
letters += letter, Python creates a new string by copying the old string plus the new character.
- This means the time complexity of building the string this way is O(n²) in the worst case (because each concatenation copies the entire string so far).
Example:
- After 1st letter: copy 1 char
- After 2nd letter: copy 2 chars
- After 3rd letter: copy 3 chars
- ...
- Total copies ≈ 1 + 2 + 3 + ... + n = O(n²)
2. List comprehension + join is efficient
- The list comprehension builds a list of characters in O(n) time.
''.join(list_of_chars) then efficiently concatenates all characters in one pass.
- This makes the overall operation O(n) time.
Summary:
| Method | Time Complexity | Why? |
|---|
letters += letter in loop | O(n²) | Creates new string every iteration |
''.join([...]) | O(n) | Builds list, then joins once |
Bonus: How to make the first one faster?
If you want to keep the loop style but avoid O(n²), use a list to collect characters, then join at the end:
letters = []
for letter in s.lower():
if letter.isalnum():
letters.append(letter)
letters = ''.join(letters)
return letters == letters[::-1]
This will be as fast as the list comprehension version.
TL;DR
- String concatenation with
+= inside a loop is slow because it copies the entire string every time.
- Building a list and joining once is fast because it avoids repeated copying.
- That’s why your second solution is faster than the first.
If you want, I can help you optimize or explain more!