Press enter to see results or esc to cancel.

Partition List Leetcode Problem 86 [Python Solution]

Welcome back, coding enthusiasts!

In this blog post, we're going to tackle a LeetCode problem called Partition List This problem falls under the category of Linked Lists and is categorized as a medium difficulty challenge.

The problem involves partitioning a linked list based on a given value, while preserving the original order of the nodes.

We'll provide you with a step-by-step Python solution and an explanation of the thought process behind it.

Let's dive in and explore this problem together.

Problem Overview

The problem statement can be summarized as follows: Given the head of a linked list and a value x, we need to partition the list in such a way that all nodes with values less than x come before nodes with values greater than or equal to x.

Importantly, we must maintain the original relative order of the nodes within each partition.

Let's take a look at a couple of examples to better understand the problem.

Example 1:

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

In this example, we have a linked list with the values [1,4,3,2,5,2], and we want to partition it based on x = 3.

As a result, we place all nodes with values less than 3 (i.e., 1, 2, 2) on the left side and nodes with values greater than or equal to 3 (i.e., 4, 3, 5) on the right side, preserving their original order.

Example 2:

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

In this example, the input list contains only two nodes, with values 2 and 1. Partitioning the list based on x = 2 places the nodes with values less than 2 (i.e., 1) on the left and the node with a value greater than or equal to 2 (i.e., 2) on the right.

Now that we understand the problem, let's proceed to the solution.

Understanding Partition List Constraints

Before delving into the code, it's essential to understand the constraints associated with the Partition List problem.

These constraints help us determine the efficiency and space requirements of our solution.

Here are the key constraints:

  • The number of nodes in the linked list is in the range of [0, 200].

This means the list can be empty or contain up to 200 nodes.
– The values of the nodes are integers in the range of [-100, 100].

The node values can be negative, zero, or positive integers.
– The value x used for partitioning is in the range of [-200, 200].

It can be any integer within this range.

Now that we've covered the problem overview and constraints, let's proceed with our Python solution.

Partition List LeetCode Problem Solution

We'll approach this problem with an efficient solution that partitions the linked list while preserving the original order.

Our Python solution leverages the use of two dummy nodes, one for the "left" partition and another for the "right" partition.

These dummy nodes will help simplify the code and make it more efficient.

def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode:
    # Create dummy nodes for left and right partitions
    less_head, bigger_head = ListNode(-1), ListNode(-1)
    less_prev, bigger_prev = less_head, bigger_head

    while head:
        if head.val < x:
            # Add the current node to the left partition
            less_prev.next = head
            less_prev = less_prev.next
        else:
            # Add the current node to the right partition
            bigger_prev.next = head
            bigger_prev = bigger_prev.next

        head = head.next

    # Terminate both partitions
    less_prev.next = bigger_prev.next = None

    # Connect the left partition to the beginning of the right partition
    less_prev.next = bigger_head.next

    # Return the resulting partitioned list
    return less_head.next

This code defines a method, partition, that takes the head of the linked list and the value x as input arguments.

It returns the head of the partitioned linked list.

The code follows these steps:

  1. Create two dummy nodes, less_head and bigger_head, for the left and right partitions, respectively.

  2. Initialize less_prev and bigger_prev to point to the dummy nodes of their respective partitions.

  3. Iterate through the original linked list, examining each node.

  4. If a node's value is less than x, add it to the left partition and update less_prev.

  5. If a node's value is greater than or equal to x, add it to the right partition and update bigger_prev.

  6. After processing all nodes, both partitions have been created.

  7. Terminate both partitions by setting their next pointers to None.

  8. Connect the end of the left partition to the beginning of the right partition.

  9. Finally, return the head of the partitioned linked list, which is less_head.next.

This solution efficiently partitions the linked list in a single pass while preserving the original order of nodes.

It achieves a time complexity of O(n), where n is the number of nodes in the linked list, and uses only a constant amount of extra space.

Time and Space Complexity

Now, let's discuss the time and space complexity of our solution.

Time Complexity: Our solution has a time complexity of O(n), where n is the number of nodes in the linked list.

This is because we traverse the entire list once, examining each node exactly once.

Space Complexity: Our solution uses a constant amount of extra space, regardless of the size of the linked list.

This means the space complexity is O(1).

Reasoning Behind Our Approach

Our approach to solving the Partition List problem is based on the fundamental concept of linked lists and involves simple, efficient manipulation of the nodes.

The use of dummy nodes for the left and right partitions simplifies the code and helps maintain efficiency.

Here's a breakdown of our reasoning:

  1. We create two dummy nodes, less_head and bigger_head, to initiate the left and right partitions.

These dummy nodes provide a starting point for building the two partitions.

  1. We maintain pointers, less_prev and bigger_prev, to track the last node in each partition.

This allows us to easily add nodes to their respective partitions and connect the partitions later.

  1. By iterating through the original linked list, we examine each node and determine whether it should be placed in the left or right partition based on the value x.

This process ensures that we preserve the original order of the nodes within each partition.

  1. After processing all nodes, we terminate both partitions by setting their next pointers to None.

This step is crucial to ensure that the resulting linked list is well-formed.

  1. Finally, we connect the end of the left partition to the beginning of the right partition.

This step completes the partitioning process and

gives us the final linked list.

Our approach focuses on maintaining efficiency, as it traverses the original list in a single pass and uses a constant amount of extra space.

The use of dummy nodes simplifies the code and reduces the need for edge case handling.

Related Interview Questions By Company:

Related Interview Questions By Difficulty:

Related Interview Questions By Category:

Conclusion

In this blog post, we've explored the Partition List LeetCode problem, which involves partitioning a linked list based on a given value while preserving the original order of nodes.

We provided a detailed Python solution that efficiently solves this problem, along with explanations for each step of the solution.

This problem not only serves as a great exercise in linked list manipulation but also demonstrates the importance of optimizing code for both time and space efficiency.

We hope this guide has been helpful, especially for beginners, and that you've gained valuable insights into tackling similar linked list problems.

If you have any questions, comments, or suggestions, please feel free to share them.

We encourage you to engage with us, as your feedback is highly valuable.

Don't forget to check out the LeetCode problem description for further practice, and stay tuned for more coding challenges and solutions.

Happy coding!

>