Skip to content

Commit c8b69d7

Browse files
committed
86. Partition List.
- Language: Python. - Time complexity: O(n). - Space complexity: O(1). - Method: Swapping node using pointers (Dummy node).
1 parent 85d5cac commit c8b69d7

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

python_solutions/lc_86_partition_list/__init__.py

Whitespace-only changes.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import Optional
2+
3+
from common_datastructures import ListNode
4+
5+
6+
class Solution:
7+
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
8+
# Time complexity: O(n). Space complexity: O(1).
9+
dummy_lt, dummy_ge = ListNode(val=-1000), ListNode(val=1000)
10+
lt, ge = dummy_lt, dummy_ge
11+
while head is not None:
12+
spam = head.next
13+
head.next = None
14+
if head.val >= x:
15+
ge.next = head
16+
ge = ge.next
17+
else:
18+
lt.next = head
19+
lt = lt.next
20+
head = spam
21+
lt.next = dummy_ge.next
22+
return dummy_lt.next
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import pytest
2+
3+
from common_datastructures import (
4+
compare_singly_linked_lists,
5+
to_list,
6+
to_singly_linked_list,
7+
)
8+
from lc_86_partition_list.lc_86_partition_list import Solution
9+
10+
test_cases = (
11+
# preset cases
12+
([1, 4, 3, 2, 5, 2], 3, [1, 2, 2, 4, 3, 5]),
13+
([2, 1], 2, [1, 2]),
14+
# common cases
15+
([4, 3, 5, -2, 0, -2], 3, [-2, 0, -2, 4, 3, 5]),
16+
([4, 3, 5, -2, 0, -2], 5, [4, 3, -2, 0, -2, 5]),
17+
([4, 3, 5, -2, 0, -2], 1, [-2, 0, -2, 4, 3, 5]),
18+
([4, 3, 5, -2, 0, -2], 0, [-2, -2, 4, 3, 5, 0]),
19+
([4, 3, 5, -2, 0, -2], -2, [4, 3, 5, -2, 0, -2]),
20+
([4, 3, 5, -2, 0, -2], 10, [4, 3, 5, -2, 0, -2]),
21+
([4, 3, 5, -2, 0, -2], -5, [4, 3, 5, -2, 0, -2]),
22+
# corner cases
23+
([-1], 2, [-1]),
24+
([5], 2, [5]),
25+
([], 2, []),
26+
)
27+
28+
29+
@pytest.mark.parametrize(("lst", "x", "ans"), test_cases)
30+
def test_success_v0(lst: list[int], x: int, ans: list[int], solution: Solution):
31+
res = solution.partition(to_singly_linked_list(lst), x)
32+
assert to_list(res) == ans
33+
assert compare_singly_linked_lists(res, to_singly_linked_list(ans))
34+
35+
36+
@pytest.fixture
37+
def solution() -> Solution:
38+
return Solution()

0 commit comments

Comments
 (0)