Leetcode 86: Partition List

grid47
grid47
Exploring patterns and algorithms
Oct 29, 2024 6 min read

A glowing line dividing a list into two perfect sections.
Solution to LeetCode 86: Partition List Problem

Given the head of a linked list and a value x, partition the list such that all nodes with values less than x appear before nodes with values greater than or equal to x. The relative order of the nodes in each partition should be preserved.
Problem
Approach
Steps
Complexity
Input: The input consists of the head of a singly linked list and an integer x. The linked list contains nodes with integer values.
Example: Input: head = [6,2,5,3,8,1], x = 5
Constraints:
• The number of nodes in the list is between 0 and 200.
• -100 <= Node.val <= 100
• -200 <= x <= 200
Output: The output should return the head of the partitioned linked list, where nodes less than x appear first, followed by nodes greater than or equal to x. The relative order of nodes in each partition should be preserved.
Example: Output: [2,3,1,6,5,8]
Constraints:
• The list should maintain the relative order of elements within each partition.
Goal: To partition the linked list around the given value x such that all nodes with values less than x come before those with values greater than or equal to x, preserving the original order of the nodes.
Steps:
• Create two separate lists: one for values less than x, and one for values greater than or equal to x.
• Traverse the original list, and for each node, append it to the appropriate list based on its value.
• Once the traversal is complete, merge the two lists by connecting the last node of the first list to the head of the second list.
Goal: The solution must be efficient enough to handle up to 200 nodes in the linked list.
Steps:
• The number of nodes in the list is between 0 and 200.
• Node values range from -100 to 100.
• The integer x lies between -200 and 200.
Assumptions:
• The input list will always be a valid linked list with the specified range of values.
• The partitioning will maintain the relative order of nodes within each partition.
Input: Input: head = [6,2,5,3,8,1], x = 5
Explanation: The list is partitioned into nodes less than 5 (2, 3, 1) and nodes greater than or equal to 5 (6, 5, 8), maintaining their relative order.

Input: Input: head = [4, 2, 7, 3], x = 5
Explanation: Nodes less than 5 (4, 2, 3) appear first, followed by nodes greater than or equal to 5 (7). The relative order of each partition is preserved.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus