CodingNodes / Linked List / Partition List System design Space play · ←→ step · R restart

Problem

You get the head of a linked list and a number x. Rearrange the nodes so that every node with a value less than x comes first, followed by every node whose value is x or more.

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

Constraints

  • 0 ≤ number of nodes ≤ 30
  • -100 ≤ Node.val ≤ 100
  • -200 ≤ x ≤ 200

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Every node is visited once and linked onto one of the two lists.

Space: Only two dummy nodes and a few pointers are added. The nodes themselves are re-linked, not copied.

Keep two growing lists, each with its own dummy node: one for values below x and one for the rest. Walk the original list once and link each node onto the end of the matching list, so the order inside each group is kept. At the end, cut the big list so it stops cleanly, then link the small list's end to the big list's front.