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 <= 200See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI