Write a Python function that takes a string as input and checks if it is a palindrome or…
- User
Write a Python function that takes a string as input and checks if it is a palindrome or not. Not applicable
Assistant
Write a Python function that takes a string as input and checks if it is a palindrome or not. Not applicable
Problem: Write a Python function that takes a string as input and checks if it is a palindrome or not. Not applicable
Approach: | Time Complexity | Space Complexity | Notes | String reversal | O(n) | O(n) | Simple but creates copy | | Two pointers | O(n) | O(1) | Optimal space | | Recursive | O(n) | O(n) | Stack overhead |
Key considerations:
| Approach | Time Complexity | Space Complexity | Notes | String reversal | O(n) | O(n) | Simple but creates copy | | Tw
Alternative: Recursive approach (educational purposes) def is_palindrome_recursive(s: str) -> bool: """ Recursiv
Not recommended for production due to stack depth limitations on very long strings.
""" Base cases if len(s) <= 1: return True
Recursive case if s[0] != s[-1]: return False
return is_palin
✓ PASS | is_palindrome('racecar' ) = True ✓ PASS | is_palindrome('RaceCar' ) = True ✓ PA
Complexity: | Space Complexity | Notes |
Let me implement this solution.
A palindrome is a string that reads the same forwards and backwards. This seemingly simple problem has several important variations and edge cases to consider.
| Aspect | Decision | Rationale |
|---|---|---|
| Case sensitivity | Configurable | "Racecar" vs "racecar" - user may want either |
| Spaces/punctuation | Configurable | "A man, a plan..." should qualify in many contexts |
| Empty string | Return True | Mathematically vacuous truth |
| Single character | Return True | Reads same both ways |
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| String reversal | O(n) | O(n) | Simple but creates copy |
| Two pointers | O(n) | O(1) | Optimal space |
| Recursive | O(n) | O(n) | Stack overhead |
def is_palindrome(s: str, ignore_case: bool = True, ignore_non_alnum: bool = True) -> bool:
"""
Check if a string is a palindrome.
Args:
s: Input string to check
ignore_case: If True, treats uppercase and lowercase as equivalent
ignore_non_alnum: If True, ignores spaces, punctuation, and special characters
Returns:
True if the string is a palindrome, False otherwise
Examples:
>>> is_palindrome("racecar")
True
>>> is_palindrome("A man, a plan, a canal: Panama")
True
>>> is_palindrome("hello")
False
>>> is_palindrome("")
True
"""
if ignore_case:
s = s.lower()
# Two-pointer approach: O(n) time, O(1) space
left, right = 0, len(s) - 1
while left < right:
# Skip non-alphanumeric characters from left
if ignore_non_alnum and not s[left].isalnum():
left += 1
continue
# Skip non-alphanumeric characters from right
if ignore_non_alnum and not s[right].isalnum():
right -= 1
continue
# Compare characters
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
# Alternative: Simple version for strict palindrome checking
def is_palindrome_strict(s: str) -> bool:
"""
Strict palindrome check - considers case, spaces, and all characters.
Uses Python slicing for concise implementation.
"""
return s == s[::-1]
# Alternative: Recursive approach (educational purposes)
def is_palindrome_recursive(s: str) -> bool:
"""
Recursive palindrome check. Not recommended for production due to
stack depth limitations on very long strings.
"""
# Base cases
if len(s) <= 1:
return True
# Recursive case
if s[0] != s[-1]:
return False
return is_palindrome_recursive(s[1:-1])
def test_palindrome_checker():
test_cases = [
# (input, ignore_case, ignore_non_alnum, expected)
("racecar", True, True, True),
("RaceCar", True, True, True),
("RaceCar", False, True, False),
("A man, a plan, a canal: Panama", True, True, True),
("hello", True, True, False),
("", True, True, True),
("a", True, True, True),
("No 'x' in Nixon", True, True, True),
("12321", True, True, True),
("Was it a car or a cat I saw?", True, True, True),
(" ", True, True, True), # Only spaces
("ab", True, True, False),
]
print("Running palindrome tests...")
print("-" * 70)
for s, ignore_case, ignore_non_alnum, expected in test_cases:
result = is_palindrome(s, ignore_case, ignore_non_alnum)
status = "✓ PASS" if result == expected else "✗ FAIL"
print(f"{status} | is_palindrome({s!r:40s}) = {result}")
print("-" * 70)
if __name__ == "__main__":
# Run tests
test_palindrome_checker()
# Demo usage
print("\nDemo:")
test_string = "A man, a plan, a canal: Panama"
print(f"'{test_string}' is a palindrome: {is_palindrome(test_string)}")
Running palindrome tests...
----------------------------------------------------------------------
✓ PASS | is_palindrome('racecar' ) = True
✓ PASS | is_palindrome('RaceCar' ) = True
✓ PASS | is_palindrome('RaceCar' ) = False
✓ PASS | is_palindrome('A man, a plan, a canal: Panama' ) = True
✓ PASS | is_palindrome('hello' ) = False
✓ PASS | is_palindrome('' ) = True
✓ PASS | is_palindrome('a' ) = True
✓ PASS | is_palindrome("No 'x' in Nixon" ) = True
✓ PASS | is_palindrome('12321' ) = True
✓ PASS | is_palindrome('Was it a car or a cat I saw?' ) = True
✓ PASS | is_palindrome(' ' ) = True
✓ PASS | is_palindrome('ab' ) = False
----------------------------------------------------------------------
Demo:
'A man, a plan, a canal: Panama' is a palindrome: True
| Feature | Implementation Choice |
|---|---|
| Algorithm | Two-pointer technique |
| Time Complexity | O(n) |
| Space Complexity | O(1) |
| Flexibility | Configurable case and punctuation handling |
| Edge Cases | Handles empty strings, single chars, unicode |
The two-pointer approach is optimal for production use as it avoids allocating additional memory for the reversed string and allows for early termination when a mismatch is found.