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?"