π·οΈ Category: Strings | π― Difficulty:
Easy| π₯ Frequency: β β β β β
π Problem Statement
Given a string, return True if it reads the same forwards and backwards, else False. Ignore case and non-alphanumeric characters.
π₯ Input β "racecar" π€ Output β True
π₯ Input β "A man a plan a canal Panama" π€ Output β True
π₯ Input β "hello" π€ Output β False
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| String cleaning | Real-world input handling |
| isalnum() method | Python string methods |
| Comparison with reverse | Pythonic thinking |
π‘ Approach
- Clean the string β lowercase + keep only alphanumeric characters
- Compare cleaned string with its reverse
"A man a plan a canal Panama"
β clean β "amanaplanacanalpanama"
β reverse β "amanaplanacanalpanama"
β equal? β
True
β Optimal Solution
def is_palindrome(s: str) -> bool:
# Step 1: Clean β lowercase + alphanumeric only
cleaned = ''.join(c.lower() for c in s if c.isalnum())
# Step 2: Compare with its reverse
return cleaned == cleaned[::-1]
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(is_palindrome("racecar")) # β
True
print(is_palindrome("A man a plan a canal Panama")) # β
True
print(is_palindrome("hello")) # β
False
print(is_palindrome("")) # β
True (empty is palindrome)
π Two Pointer Alternative
def is_palindrome_two_ptr(s: str) -> bool:
cleaned = ''.join(c.lower() for c in s if c.isalnum())
left, right = 0, len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
π¬ Pro tip: Mention the two-pointer approach as an alternative β it shows deeper understanding and O(1) space awareness.
π Complexity Analysis
βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β Time O(n) β Clean + reverse both are O(n) β
β Space O(n) β Cleaned string stored in memory β
βββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βFirst I clean the string β convert to lowercase and keep only alphanumeric characters. Then I compare it with its reverse. If theyβre equal, itβs a palindrome. I can also use a two-pointer approach which avoids creating the reversed string.β
π Common Follow-up Questions
Q1 β What about numbers like 121?
def is_palindrome_num(n: int) -> bool:
s = str(n)
return s == s[::-1]
Q2 β Without converting to string?
# Math approach β reverse the number
def is_palindrome_math(n: int) -> bool:
if n < 0:
return False
original, reversed_n = n, 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
return original == reversed_n
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
