InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Partition List

medium Original ↗ 00:00

Problem

Given the head of a singly linked list and an integer x, rearrange the list so that every node with value less than x appears before every node with value greater than or equal to x.

The partition must be stable: within each of the two groups, nodes keep their original relative order.

Examples

  • Input: head = [1, 4, 3, 2, 5, 2], x = 3 → Output: [1, 2, 2, 4, 3, 5] Values < 3 are 1, 2, 2 (original order kept); values >= 3 are 4, 3, 5 (original order kept).
  • Input: head = [2, 1], x = 2 → Output: [1, 2] 1 < 2 moves ahead of 2, which is >= 2.
  • Input: head = [5, 6, 7], x = 3 → Output: [5, 6, 7] No value is below 3, so nothing moves.

Constraints

  • 0 <= n <= 200 where n is the number of nodes.
  • -100 <= Node.val <= 100, -200 <= x <= 200.

The list is small, so most approaches pass. The exercise targets the O(n)-time, O(1)-extra-space pointer solution and correct stability.

Think about it first

Hint 1 Quicksort-style in-place swapping breaks the required stability. What data-structure-free way is there to keep two groups in original order?
Hint 2 Imagine dealing the nodes, one pass, into two separate lists: a "less than x" list and a "greater or equal" list. Appending each node to a tail keeps its group in original order.
Hint 3 Use two dummy head nodes. Walk the original list once, appending each node to the matching tail. Then set the greater tail's next to None and connect the less tail to the greater dummy's first real node.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug