Skip to content

Commit 97f85bb

Browse files
Update is_palindrome.py
Algorithm optimised in terms of space from O(n) to O(1)
1 parent d141fa8 commit 97f85bb

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

strings/is_palindrome.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,20 @@ def is_palindrome(s: str) -> bool:
1616
# Since punctuation, capitalization, and spaces are often ignored while checking
1717
# palindromes, we first remove them from our string.
1818
s = "".join(character for character in s.lower() if character.isalnum())
19-
return s == s[::-1]
19+
# return s == s[::-1] the slicing method uses extra spaces, we can do better with iteration method.
20+
21+
end=len(s)//2
22+
n=len(s)
23+
24+
#We need to traverse till half of the length of string
25+
#as we can get access of the i'th last element from i'th index.
26+
#eg: [0,1,2,3,4,5] => 4th index can be accessed with the help of 1st index (i==n-i-1)
27+
#where n is length of string
28+
29+
for i in range(end):
30+
if s[i]!=s[n-i-1]:
31+
return False
32+
return True
2033

2134

2235
if __name__ == "__main__":

0 commit comments

Comments
 (0)