Skip to content

Commit 82d002b

Browse files
committed
constant space soln
1 parent 7be8347 commit 82d002b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Python/chapter02/2.6 - Palindrome/miguel_2.6_soln.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
"""
88
import unittest
9+
import math
910

1011

1112
class Node:
@@ -154,6 +155,29 @@ def reverse_linked_list(ll: LinkedList) -> LinkedList:
154155
return output_ll
155156

156157

158+
def palindrome_constant_space(ll: LinkedList) -> bool:
159+
"""
160+
Same as the palindrome function below, but
161+
with constant space
162+
Runtime: O(n^2)
163+
Space Complexity: O(1)
164+
:param ll: an input linked list
165+
:return: true if ll is a palindrome, false otherwise
166+
"""
167+
n1 = ll.head
168+
for i in range(math.ceil(ll.size/2)):
169+
curr_data = n1.data
170+
n2 = n1
171+
# advance n2 pointer to desired complement index
172+
for j in range(i, ll.size - i - 1):
173+
n2 = n2.next
174+
# if not the same, then not a palindrome
175+
if n2.data != curr_data:
176+
return False
177+
n1 = n1.next
178+
return True
179+
180+
157181
def palindrome(ll: LinkedList) -> bool:
158182
"""
159183
Given a linked list, this function will check if the
@@ -213,6 +237,10 @@ def test_palindrome(self):
213237
for ll, expected in self.test_cases:
214238
self.assertEqual(palindrome(ll), expected, msg=ll)
215239

240+
def test_palindrome_constant_space(self):
241+
for ll, expected in self.test_cases:
242+
self.assertEqual(palindrome_constant_space(ll), expected, msg=ll)
243+
216244

217245
if __name__ == '__main__':
218246
unittest.main()

0 commit comments

Comments
 (0)