Skip to content

Commit d815b62

Browse files
committed
update soln to O(n)
1 parent e7369d7 commit d815b62

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

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

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ def _append_node(self, n: Node) -> None:
5656
self.tail = self.head
5757
else:
5858
end = n
59-
self.tail.next = end
6059
self.tail = end
6160
self.size += 1
6261

@@ -159,22 +158,30 @@ def is_palindrome_constant_space(ll: LinkedList) -> bool:
159158
"""
160159
Same as the palindrome function below, but
161160
with constant space
162-
Runtime: O(n^2)
161+
Runtime: O(n)
163162
Space Complexity: O(1)
164163
:param ll: an input linked list
165164
:return: true if ll is a palindrome, false otherwise
166165
"""
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:
166+
# reverse half of the linked list
167+
temp_ll1 = LinkedList()
168+
temp_ll2 = LinkedList()
169+
n = ll.head
170+
for _ in range(math.ceil(ll.size/2)):
171+
temp_ll1.append_to_tail(n) # first half
172+
n = n.next
173+
while n is not None:
174+
temp_ll2.append_to_tail(n) # second half
175+
n = n.next
176+
temp_ll2.reverse()
177+
# compare temp_ll and ll
178+
n1 = temp_ll1.head
179+
n2 = temp_ll2.head
180+
for _ in range(temp_ll2.size):
181+
if n1.data != n2.data:
176182
return False
177183
n1 = n1.next
184+
n2 = n2.next
178185
return True
179186

180187

0 commit comments

Comments
 (0)