π Merge Sort for Linked List β Python (Efficient Sorting)
Hi All,
Today I solved an advanced problem: Sorting a Linked List using Merge Sort.
π Problem Statement
Given the head of a singly linked list, sort the list using Merge Sort algorithm.
π Example
Input:
10 -> 30 -> 20 -> 50 -> 40 -> 60
Output:
10 -> 20 -> 30 -> 40 -> 50 -> 60
π‘ Why Merge Sort for Linked List?
π Unlike arrays:
- Linked lists donβt support random access
- Merge sort works efficiently with pointers
π‘ Approach
πΉ Divide and Conquer
- Find middle of list
- Split into two halves
- Recursively sort both halves
- Merge sorted lists
π§ Step-by-Step Logic
Step 1: Find Middle
- Use slow and fast pointers
Step 2: Split List
- Break list into two halves
Step 3: Sort Recursively
Step 4: Merge Two Sorted Lists
π» Python Code
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
# Function to merge two sorted lists
def merge(l1, l2):
dummy = ListNode(0)
tail = dummy
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
if l2:
tail.next = l2
return dummy.next
# Function to find middle of list
def get_middle(head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# Merge Sort function
def merge_sort(head):
if not head or not head.next:
return head
# Find middle
mid = get_middle(head)
right = mid.next
mid.next = None # split
left = head
# Sort both halves
left = merge_sort(left)
right = merge_sort(right)
# Merge sorted halves
return merge(left, right)
π Dry Run
For:
10 -> 30 -> 20 -> 50
Steps:
- Split β [10,30] and [20,50]
- Sort β [10,30], [20,50]
- Merge β [10,20,30,50]
π₯οΈ Sample Output
Input: 10 -> 30 -> 20 -> 50 -> 40 -> 60
Output: 10 -> 20 -> 30 -> 40 -> 50 -> 60
β‘ Complexity Analysis
- Time Complexity: O(n log n) β
- Space Complexity: O(log n) (recursion)
π§ Why this is important?
- Best sorting method for linked list
- Uses divide & conquer
- Frequently asked in interviews
β Conclusion
This problem helped me understand:
- Merge Sort in linked lists
- Fast & slow pointer technique
- Efficient sorting without extra arrays
π Must-know for coding interviews!
Top comments (0)