-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidpalindromeDay6.py
More file actions
45 lines (33 loc) · 1.12 KB
/
Copy pathValidpalindromeDay6.py
File metadata and controls
45 lines (33 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#Brute Force Approach
# class Solution:
# def isPalindrome(self, s: str) -> bool:
# cleaned = ''
# for char in s:
# if char.isalnum():
# cleaned += char.lower()
# return cleaned == cleaned[::-1]
# Time Complexity: O(n)
# Space Complexity: O(n) (due to cleaned string and reverse)
#Brute Approach
# class Solution:
# def isPalindrome(self, s: str) -> bool:
# chars = [char.lower() for char in s if char.isalnum()]
# return chars == chars[::-1]
# Time Complexity: O(n)
# Space Complexity: O(n) (still creating a list)
#Optimal Approach
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
# Time Complexity: O(n)
# Space Complexity: O(1) (in-place comparison, no extra space)