Problem 202213 · medium · Level 02 Linear Data Structures

Stable Partition Around a Pivot

linked list · two lists · partition

Given the head of a singly linked list and an integer x, rearrange the nodes so that every node with a value less than x comes before every node with a value greater than or equal to x. Inside each of the two groups the nodes must keep their original relative order. Return the head.

Examples

Input:  head = 6 -> 2 -> 9 -> 5 -> 4 -> 7 -> 1, x = 5
Output: 2 -> 4 -> 1 -> 6 -> 9 -> 5 -> 7
Explanation: 5 is not less than 5, so it goes with the second group.

Input:  head = 7 -> 7 -> 2, x = 7
Output: 2 -> 7 -> 7

Constraints

  • Target: O(n) time, O(1) extra space, one pass; relink nodes rather than copying values

Goals

  • Distribute nodes into two chains and join them
  • Preserve the original relative order inside each group
Starting Python…