Skip to content

Commit 307aa65

Browse files
committed
#125 : Valid Palindrome solution
1 parent 44a3f84 commit 307aa65

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

valid-palindrome/heesun-task.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# 125. Valid Palindrome
2+
# Solution 1: Can early return False if chars don't match, so O(1) space.
3+
# Solution 2: Normalize the string first, then check if it's a palindrome. O(n) space for the normalized string.
4+
5+
class Solution:
6+
# Time Complexity: O(n)
7+
# Space Complexity: O(1)
8+
def isPalindrome(self, s: str) -> bool:
9+
# Use two pointers from both ends
10+
left, right = 0, len(s) - 1
11+
12+
# Move inward from both ends, ignore non-alphanumeric chars
13+
# and compare chars case-insensitively.
14+
while left < right:
15+
while left < right and not s[left].isalnum():
16+
left += 1
17+
while left < right and not s[right].isalnum():
18+
right -= 1
19+
if s[left].lower() != s[right].lower():
20+
return False
21+
left += 1
22+
right -= 1
23+
return True
24+
25+
26+
# Time Complexity: O(n)
27+
# Space Complexity: O(n)
28+
def isPalindrome2(self, s:str) -> bool:
29+
# Normalize the string by keeping only lowercase alphanumeric characters
30+
s = list(filter(str.isalnum, s.lower()))
31+
32+
# Check if the list is the same forwards and backwards
33+
return s == s[::-1]

0 commit comments

Comments
 (0)