Solving Leetcode Interviews in Seconds with AI: Sort List
Introduction
In this blog post, we will explore how to solve the LeetCode problem "148" 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, return the list after sorting it in ascending order. Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is in the range [0, 5 * 104]. -105 <= Node.val <= 105 Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Explanation
Here's a breakdown of the approach, complexity analysis, and the Python code for sorting a linked list efficiently:
- Merge Sort: The primary algorithm used is merge sort. Merge sort is well-suited for linked lists because it doesn't require random access to elements like quicksort.
- Divide and Conquer: The list is recursively divided into smaller sublists until each sublist contains only one element (which is inherently sorted).
Merge: The sorted sublists are then merged back together in a sorted manner until the entire list is sorted.
Time Complexity: O(n log n), Space Complexity: O(1) (in-place merge sort)
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def sortList(head):
"""
Sorts a linked list in ascending order using merge sort.
Args:
head: The head of the linked list.
Returns:
The head of the sorted linked list.
"""
if not head or not head.next:
return head # Base case: empty or single-node list is already sorted
# 1. Split the list into two halves
middle = get_middle(head)
next_to_middle = middle.next
middle.next = None # Disconnect the two halves
# 2. Recursively sort the two halves
left = sortList(head)
right = sortList(next_to_middle)
# 3. Merge the sorted halves
sorted_list = merge(left, right)
return sorted_list
def get_middle(head):
"""
Finds the middle node of a linked list using the slow and fast pointer approach.
"""
if not head:
return head
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(left, right):
"""
Merges two sorted linked lists into a single sorted linked list.
"""
dummy_head = ListNode() # Dummy node to simplify the merging process
tail = dummy_head
while left and right:
if left.val <= right.val:
tail.next = left
left = left.next
else:
tail.next = right
right = right.next
tail = tail.next
# Append any remaining nodes from either list
if left:
tail.next = left
if right:
tail.next = right
return dummy_head.next # Return the head of the merged list (excluding dummy node)