Skip to problem
←

Partition List

Medium 0 attempts

Given the head of a singly linked list and a threshold x, rearrange the original nodes into two groups: nodes with values less than x, followed by nodes with values greater than or equal to x.

Preserve the original relative order within each group. This is a stable partition, not a sort. Do not change node values or replace the nodes with copies. Return the new head, or null for an empty list.

For head = [1, 4, 3, 2, 5, 2] and x = 3, the result is [1, 2, 2, 4, 3, 5]. The second group remains [4, 3, 5] in its original order, and values equal to x belong to that group.

Examples display lists as arrays; your function receives nodes with val and next properties.

Function contract

Implement partition(head, x). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head of the stably partitioned original nodes. The runner displays the resulting list as a value array; null is [].

Example 1

Input
head = [1,4,3,2,5,2]
x = 3
Output
[1,2,2,4,3,5]

Example 2

Input
head = []
x = 3
Output
[]
Constraints
  • 0 to 200 nodes
  • -100 <= Node.val <= 100
  • -200 <= x <= 200
Topics

Two Lists

Use two dummy heads and two tail pointers. Walk the original list once, appending each node to the appropriate tail. Appending in traversal order preserves relative order in both groups.

After the scan, set the second tail's next to null. This is essential: its old link might point back into the first group, which would create a cycle when the groups are joined. Connect the first tail to the second group's head and return the first dummy's next node. Empty groups need no special handling.

The dummy heads are temporary helpers; every node in the returned list is an original node with its original value.

javascript
function partition(head, x) {
  const before = { next: null },
    after = { next: null };
  let b = before,
    a = after;
  while (head) {
    if (head.val < x) {
      b.next = head;
      b = b.next;
    } else {
      a.next = head;
      a = a.next;
    }
    head = head.next;
  }
  a.next = null;
  b.next = after.next;
  return before.next;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript