Valid Palindrome Two Pointer in DSA Python - Time & Space Complexity
We want to know how the time taken to check if a string is a palindrome grows as the string gets longer.
Specifically, how many steps does the two-pointer method take as input size increases?
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 using two pointers moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing characters at two positions in the string.
- How many times: At most, half the length of the string (n/2) times.
As the string length grows, the number of 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, but only half as many checks are needed.
Time Complexity: O(n)
This means the time to check grows directly in proportion to the string length.
[X] Wrong: "The two-pointer method checks every character twice, so it takes O(2n) time."
[OK] Correct: The method compares pairs from both ends simultaneously, so it only needs about n/2 comparisons, which is still O(n) because constants are ignored.
Understanding this simple linear time check helps build confidence for string problems and shows you can reason about efficient scanning techniques.
"What if we ignored non-alphanumeric characters and spaces? How would the time complexity change?"
Practice
Solution
Step 1: Understand two-pointer technique
Two pointers start at the beginning and end of the string.Step 2: Compare characters moving inward
Characters at both pointers are compared; pointers move closer if equal.Final Answer:
It compares characters from the start and end moving towards the center -> Option BQuick Check:
Two-pointer palindrome check = comparing ends [OK]
- Thinking it reverses the string
- Checking only vowels or sorting characters
- Using one pointer only
Solution
Step 1: Identify pointer start positions
Left pointer starts at 0 (first character), right pointer at last index (length - 1).Step 2: Check syntax correctness
left = 0; right = len(s) - 1 correctly sets left=0 and right=len(s)-1 for valid indexing.Final Answer:
left = 0; right = len(s) - 1 -> Option DQuick Check:
Start pointers at 0 and last index [OK]
- Starting right pointer at length (out of range)
- Starting left pointer at 1 (skips first char)
- Using negative or invalid indices
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome('racecar'))
print(is_palindrome('hello'))Solution
Step 1: Check 'racecar' palindrome
Characters match from both ends, so returns True.Step 2: Check 'hello' palindrome
Characters differ ('h' != 'o'), returns False.Final Answer:
True\nFalse -> Option CQuick Check:
'racecar' palindrome = True, 'hello' not = False [OK]
- Assuming 'hello' is palindrome
- Returning True without full check
- Mixing up True/False outputs
def check_palindrome(s):
left, right = 0, len(s)
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return TrueSolution
Step 1: Check pointer initialization
Right pointer is set to len(s), which is out of string index range.Step 2: Correct pointer initialization
Right should be len(s) - 1 to point to last character index.Final Answer:
right should be initialized as len(s) - 1 -> Option AQuick Check:
Right pointer must be last index, not length [OK]
- Using len(s) as index causes IndexError
- Changing left pointer start incorrectly
- Incorrect loop condition
s = "A man, a plan, a canal: Panama", which modification is needed in the two-pointer palindrome check to correctly identify it as a palindrome?Solution
Step 1: Understand input complexity
String contains spaces, commas, and mixed case which affect direct comparison.Step 2: Modify comparison logic
Skip non-alphanumeric characters and compare lowercase versions to ignore case and symbols.Step 3: Why other options fail
Reversing or uppercase alone won't ignore spaces/punctuation; vowels only is incorrect.Final Answer:
Ignore non-alphanumeric characters and case during comparison -> Option AQuick Check:
Clean string and ignore case for palindrome check [OK]
- Not ignoring punctuation and spaces
- Only changing case without skipping symbols
- Comparing vowels only
Ready to prove it?
Pass the test and this pattern moves unknown
