AlgoMaster Logo

Partition List

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Two-Pass: Array-based Partition

Intuition:

The idea is to first convert the linked list into an array, partition the array into two parts, and then reconstruct the linked list. Although not the most efficient, it provides a clear separation of the partition logic.

Steps:

  1. Traverse through the original list and populate the values into an array.
  2. Partition the array into two separate lists - one containing elements less than x and the other containing elements greater than or equal to x.
  3. Traverse through these two lists and create a new linked list with the required order.

Code:

2. Two-Pointer: Single-pass LinkedList

Intuition:

Using two pointers, we directly manipulate the linked list to partition without extra space. This is achieved by creating two dummy head nodes representing partitions for values less than x and for values greater than or equal to x.

Steps:

  1. Initialize two dummy nodes lessHead and greaterHead to handle partitions.
  2. Iterate through the list, linking nodes with values less than x to less and others to greater.
  3. Connect the less list with the greater list.
  4. The new head is the start of the less list.

Code: