Partition List

Medium · Linked Lists · Linked List · Two Pointers

Problem

Given the head of a linked list and a value 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.

Within each of the two groups, keep the nodes in their original relative order. Return the head of the rearranged list.

Examples

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

1, 2 and 3 are below 4 and move ahead of 5, 4 and 6; both groups keep their order.

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

Only 1 is smaller than 2.

Input: head = [], x = 0
Output: []

There are no nodes to move.

Constraints

Approaches

Follow-up

Two chains joined at the end is a stable partition in O(1) extra space. The use cases ask the same thing of arrays, and split into three groups instead of two.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…