Problem description

You are given the head of a linked list and a target value x. Rearrange the list so that every node whose value is strictly less than x appears before every node whose value is greater than or equal to x.

Within each of the two groups, the nodes must keep the same relative order they had in the original list. Return the head of the reordered list.

Example 1

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

Output: [1,2,2,4,3,5]

The nodes less than 3 are 1, 2, 2 (in that order) and the rest are 4, 3, 5 (in that order). Concatenating the two groups preserves both orderings.

Example 2

Input: head = [2,1], x = 2

Output: [1,2]

Only the node 1 is below the threshold, so it moves ahead of the node 2, which is greater than or equal to x.

Constraints

  • The number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

After the pattern

Now solve one you haven't seen.

Retether the Sensor Pods is our own problem on the technique behind Partition List: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free