0
0
DSA Pythonprogramming~5 mins

Palindrome Detection in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Palindrome Detection
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the string gets longer, the number of character comparisons grows roughly half as fast.

Input Size (n)Approx. Operations
105 comparisons
10050 comparisons
1000500 comparisons

Pattern observation: The number of steps grows linearly with input size, just half as many checks are needed.

Final Time Complexity

Time Complexity: O(n)

This means the time to check a palindrome grows in a straight line with the length of the string.

Common Mistake

[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.

Interview Connect

Understanding how palindrome checking scales helps you explain your code clearly and shows you can analyze simple algorithms well.

Self-Check

"What if we used recursion instead of a loop? How would the time complexity change?"