Post

Created by @oliverrichards
 at November 23rd 2023, 9:53:15 pm.

Technical Interview Question: Write a function to partition a linked list around a given value x, such that all nodes with values less than x come before all nodes with values greater than or equal to x. In other words, re-arrange the nodes so that all nodes less than x appear before all nodes greater than or equal to x, while preserving the original relative order of the nodes within each group.

You are given the definition of a singly linked list node:

class ListNode {
  public int val;
  public ListNode next;

  ListNode(int val) {
    this.val = val;
  }
}

Write a function partition that takes in the head of the linked list and an integer x, and returns the head of the modified linked list.

Example: Input: 1 -> 4 -> 3 -> 2 -> 5 -> 2, x = 3 Output: 1 -> 2 -> 2 -> 4 -> 3 -> 5

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode curr1 = dummy1;
        ListNode curr2 = dummy2;
        ListNode curr = head;

        while (curr != null) {
            if (curr.val < x) {
                curr1.next = curr;
                curr1 = curr;
            } else {
                curr2.next = curr;
                curr2 = curr;
            }
            curr = curr.next;
        }

        curr2.next = null; // set end of greater/equal list to null
        curr1.next = dummy2.next; // connect end of less list to greater/equal list's head

        return dummy1.next;
    }
}

Explanation:

  1. We create two dummy nodes dummy1 and dummy2 to represent two partitions: one for nodes less than x, and the other for nodes greater than or equal to x.
  2. We iterate through the original linked list and for each node, we check if its value is less than x. If it is, we append it to the first partition (dummy1), else we append it to the second partition (dummy2).
  3. Once we have iterated through the original list, we set the end of the second partition (dummy2) to null to disconnect it from the original list, and connect the end of the first partition to the head of the second partition.
  4. Finally, we return the head of the modified list, which is now partitioned based on the value x.