Skip to content

Commit 2631a15

Browse files
committed
constant space complexity attempt
1 parent 89f84d3 commit 2631a15

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

Python/chapter02/2.4 - Partition/miguel_2.4_soln.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
Result: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
1515
"""
1616
import unittest
17+
from typing import Optional
1718

1819

1920
class Node:
@@ -41,7 +42,13 @@ def __init__(self, *numbers: int):
4142
for num in numbers:
4243
self.append_to_tail(num)
4344

44-
def append_to_tail(self, d: int) -> None:
45+
def append_to_tail(self, e) -> None:
46+
if isinstance(e, int):
47+
self._append_num(e)
48+
elif isinstance(e, Node) or e is None:
49+
self._append_node(e)
50+
51+
def _append_num(self, d: int) -> None:
4552
if self.head is None:
4653
self.head = Node(d)
4754
self.tail = self.head
@@ -51,6 +58,16 @@ def append_to_tail(self, d: int) -> None:
5158
self.tail = end
5259
self.size += 1
5360

61+
def _append_node(self, n: Optional[Node] = None) -> None:
62+
if self.head is None:
63+
self.head = n
64+
self.tail = self.head
65+
else:
66+
end = n
67+
self.tail.next = end
68+
self.tail = end
69+
self.size += 1
70+
5471
def append_to_head(self, d: int) -> None:
5572
new_head = Node(d)
5673
new_head.next = self.head
@@ -134,23 +151,28 @@ def partition_ll(ll: LinkedList, pivot: int) -> LinkedList:
134151
elements less than x. They do not need to appear
135152
in between the left and right partitions.
136153
Runtime: O(n)
137-
Space Complexity: O(n)
154+
Space Complexity: O(1)
138155
:param ll: an input linked list
139156
:param pivot: a number to partition around
140157
:return: a linked list that is 'partitioned'
141158
"""
142-
left_partition = [] # will contain values < pivot
143-
right_partition = [] # will contain values >= pivot
159+
left_partition = LinkedList() # will contain values < pivot
160+
right_partition = LinkedList() # will contain values >= pivot
144161

145162
n = ll.head
146163
while n is not None:
147164
if n.data < pivot:
148-
left_partition.append(n.data)
165+
left_partition.append_to_tail(n)
149166
else:
150-
right_partition.append(n.data)
167+
right_partition.append_to_tail(n)
151168
n = n.next
169+
# last element may still be pointing
170+
# to earlier elements that are less than
171+
# pivot so we need to cut that link
172+
right_partition.append_to_tail(None)
152173
# then, merge left and right partition lists into one linked list
153-
return LinkedList(*left_partition, *right_partition)
174+
left_partition.tail.next = right_partition.head
175+
return left_partition
154176

155177

156178
class TestPartition(unittest.TestCase):

0 commit comments

Comments
 (0)