File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
Python/chapter02/2.6 - Palindrome Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 6
6
7
7
"""
8
8
import unittest
9
+ import math
9
10
10
11
11
12
class Node :
@@ -154,6 +155,29 @@ def reverse_linked_list(ll: LinkedList) -> LinkedList:
154
155
return output_ll
155
156
156
157
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
+
157
181
def palindrome (ll : LinkedList ) -> bool :
158
182
"""
159
183
Given a linked list, this function will check if the
@@ -213,6 +237,10 @@ def test_palindrome(self):
213
237
for ll , expected in self .test_cases :
214
238
self .assertEqual (palindrome (ll ), expected , msg = ll )
215
239
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
+
216
244
217
245
if __name__ == '__main__' :
218
246
unittest .main ()
You can’t perform that action at this time.
0 commit comments