Palindrome Check
Two Pointers
๐ Problem Statement
Given a string, return True if it reads the same forward and backward, and False otherwise. For example, "racecar" is a palindrome, "hello" is not. A single character like "a" is always a palindrome.
๐ก Intuition
A palindrome is symmetric: for all . This is the same two-pointer technique used for array reversal โ compare from both ends and move inward. Finding any mismatch lets us immediately return False (early exit).
๐ง Approach
- Initialize two pointers:
left = 0,right = len(s) - 1. - While
left < right, compares[left]withs[right]. - If they differ, return False immediately.
- If they match, move
leftforward andrightbackward. - If the loop completes without mismatches, return True.
โก Complexity Analysis
Time
where is the length of the string โ at most comparisons
Space
โ only two pointer variables, no extra data structures
โ ๏ธ Common Mistakes
- Comparing with
s == s[::-1]โ correct but uses extra space - Not handling case sensitivity: "Racecar" returns False unless normalized to lowercase first
- Forgetting edge cases: empty string
""and single character"a"are both palindromes
๐ฏ Final Thoughts
This problem reinforces the two-pointer pattern from Day 4 (Array Reversal). Strings in Python are essentially character arrays, so the same pointer logic applies.