Palindrome Detection in DSA Python - Time & Space Complexity
We want to know how the time to check if a word or phrase is a palindrome changes as the input gets longer.
How does the number of steps grow when the input size grows?
Analyze the time complexity of the following code snippet.
def is_palindrome(s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
This code checks if a string reads the same forwards and backwards by comparing characters from both ends moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing characters at positions from the start and end of the string.
- How many times: Up to half the length of the string (n/2) comparisons in the worst case.
As the string gets longer, the number of character comparisons grows roughly half as fast.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 comparisons |
| 100 | 50 comparisons |
| 1000 | 500 comparisons |
Pattern observation: The number of steps grows linearly with input size, just half as many checks are needed.
Time Complexity: O(n)
This means the time to check a palindrome grows in a straight line with the length of the string.
[X] Wrong: "Checking a palindrome takes constant time because you just compare the first and last characters."
[OK] Correct: You must compare pairs of characters moving inward until the middle, so the time grows with the string length.
Understanding how palindrome checking scales helps you explain your code clearly and shows you can analyze simple algorithms well.
"What if we used recursion instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand palindrome definition
A palindrome is a word or phrase that reads the same forwards and backwards.Step 2: Compare options with definition
Only It reads the same forwards and backwards matches this definition exactly.Final Answer:
It reads the same forwards and backwards -> Option BQuick Check:
Palindrome = Same forwards and backwards [OK]
- Thinking palindrome means only letters
- Assuming even length only
- Confusing start/end letters with palindrome
s is a palindrome?Solution
Step 1: Understand string reversal in Python
The slices[::-1]returns the reversed string.Step 2: Check each option
s == s[::-1] comparessto its reversed slice correctly. s == reversed(s) compares to an iterator, not a string. s == s.reverse() tries to usereverse()which is a list method and returns None. s == s[1:] compares to a substring missing the first character.Final Answer:
s == s[::-1] -> Option DQuick Check:
Use slicing to reverse string [OK]
- Using reversed() without join
- Calling reverse() on string
- Comparing to wrong substring
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome('level'))
print(is_palindrome('world'))Solution
Step 1: Check 'level' palindrome status
'level' reversed is 'level', sois_palindrome('level')returns True.Step 2: Check 'world' palindrome status
'world' reversed is 'dlrow', which is different, sois_palindrome('world')returns False.Final Answer:
True\nFalse -> Option AQuick Check:
'level' palindrome True, 'world' not [OK]
- Assuming all strings are palindrome
- Mixing output order
- Confusing print output format
def check_palindrome(s):
for i in range(len(s)):
if s[i] != s[len(s)-i]:
return False
return TrueSolution
Step 1: Analyze index usage in loop
Indexlen(s)-iis out of range because string indices go from 0 to len(s)-1.Step 2: Identify correct index for reverse comparison
It should belen(s)-i-1to avoid index error.Final Answer:
Index out of range error in s[len(s)-i] -> Option CQuick Check:
Check index bounds carefully [OK]
- Off-by-one error in indexing
- Looping full length instead of half
- Ignoring index errors
Solution
Step 1: Understand requirements
We must ignore spaces and capitalization, and consider only letters.Step 2: Analyze each option
s_clean = ''.join(c.lower() for c in s if c.isalpha())\nreturn s_clean == s_clean[::-1] removes non-letters and lowercases all characters, then checks palindrome. s_clean = s.replace(' ', '')\nreturn s_clean == s_clean[::-1] only removes spaces but keeps punctuation and case. s_clean = s.lower()\nreturn s_clean == s_clean[::-1] keeps punctuation and spaces. s_clean = ''.join(c for c in s if c.isdigit())\nreturn s_clean == s_clean[::-1] keeps digits only, ignoring letters.Final Answer:
s_clean = ''.join(c.lower() for c in s if c.isalpha())\nreturn s_clean == s_clean[::-1] -> Option AQuick Check:
Filter letters and lowercase before palindrome check [OK]
- Only removing spaces
- Ignoring punctuation
- Not lowercasing letters
Ready to prove it?
Pass the test and this pattern moves unknown
