Solving Leetcode Interviews in Seconds with AI: Partition List
Introduction
In this blog post, we will explore how to solve the LeetCode problem "86" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5] Example 2: Input: head = [2,1], x = 2 Output: [1,2] Constraints: The number of nodes in the list is in the range [0, 200]. -100 <= Node.val <= 100 -200 <= x <= 200
Explanation
Here's an efficient solution to partition a linked list around a given value x, preserving the original order of elements within each partition.
High-Level Approach:
- Create two separate linked lists: one for nodes with values less than
xand another for nodes with values greater than or equal tox. - Iterate through the original linked list, appending each node to the appropriate new list based on its value compared to
x. - Concatenate the "less than" list with the "greater than or equal to" list.
- Create two separate linked lists: one for nodes with values less than
Complexity:
- Runtime Complexity: O(n), where n is the number of nodes in the linked list.
- Storage Complexity: O(1) - constant extra space. We are using pointers only.
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def partition(head: ListNode, x: int) -> ListNode:
"""
Partitions a linked list such that all nodes less than x come before nodes greater than or equal to x.
The original relative order of the nodes in each of the two partitions is preserved.
"""
less_head = ListNode()
greater_equal_head = ListNode()
less_tail = less_head
greater_equal_tail = greater_equal_head
curr = head
while curr:
if curr.val < x:
less_tail.next = curr
less_tail = curr
else:
greater_equal_tail.next = curr
greater_equal_tail = curr
curr = curr.next
less_tail.next = greater_equal_head.next
greater_equal_tail.next = None # Important: Terminate the second list
return less_head.next