Leetcode: Partition List
1 min readDec 26, 2016
We need to maintain lower and higher lists
- Create 2 lists for storing the nodes with lower and higher values
- To handle corner cases efficiently use dummy head nodes
- Iterate over the given list and append node to the lower list if its value is lower than given number otherwise append it to higher list
- Connect the lower list to higher list and return head of lower list
Remarks:
- O(n) time complexity for iterating the list once. Note that every problem related to lists can be solved with linear complexity as you only need to iterate over the list a constant number of times
- O(1) space complexity for using 4 additional variables
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
a, b = ListNode(0), ListNode(-1)
head1, head2 = a, b
while head:
if head.val < x:
a.next = head
a = a.next
else:
b.next = head
b = b.next
head = head.next
a.next, b.next = head2.next, None
return head1.next