Given the head of a linked list and a value x
, partition it such that all nodes less than x
come before nodes greater than or equal to x
.
You should preserve the original relative order of the nodes in each of the two partitions.
For example:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
x
?
x
.We will use two separate lists (or linked lists) to partition the given linked list:
before
) will store all nodes with values less than x
.after
) will store nodes with values greater than or equal to x
.We will maintain two pointers for each partitioned list (before_head
, before_tail
and after_head
, after_tail
) to facilitate efficient appending.
Steps:
before
list or the after
list based on the node’s value.next
pointer of the last node of the before
list to the first node of the after
list.before
list will be the new head of the modified list.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def partition(head: ListNode, x: int) -> ListNode:
if not head:
return head
before_head = ListNode(0)
before_tail = before_head
after_head = ListNode(0)
after_tail = after_head
current = head
while current:
if current.val < x:
before_tail.next = current
before_tail = before_tail.next
else:
after_tail.next = current
after_tail = after_tail.next
current = current.next
# Terminate `after` list to prevent potential cycles
after_tail.next = None
# Combine partitioned lists
before_tail.next = after_head.next
return before_head.next
The solution traverses the list once to partition it, which results in a time complexity of O(n)
, where n
is the number of nodes in the linked list. The space complexity is O(1)
excluding the space needed for the output linked list, since we are only using a fixed number of additional pointers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?