LinkedListProblem 13 of 36
Merge Sort For Linked lists [Very Important]
Merge Sort for Linked Lists
Problem Statement
Given the head of a linked list, sort it in ascending order using merge sort algorithm. Merge sort is particularly well-suited for linked lists because it doesn't require random access to elements.
Example
Input: 4 -> 2 -> 1 -> 3 -> null
Output: 1 -> 2 -> 3 -> 4 -> null
Input: -1 -> 5 -> 3 -> 4 -> 0 -> null
Output: -1 -> 0 -> 3 -> 4 -> 5 -> null
Input: null
Output: null
Brute Force Approach (Bubble Sort / Selection Sort)
Intuition
We can use simple sorting algorithms like bubble sort on linked lists by repeatedly swapping values. However, this is O(n²) which is inefficient.
Algorithm (Bubble Sort)
- Repeat n times:
- Traverse the list
- If current value > next value, swap values
- Continue until no swaps needed
Implementation
Complexity Analysis
- Time Complexity: O(n²) - Nested iterations
- Space Complexity: O(1) - Only swapping values
Optimal Approach (Merge Sort)
Intuition
Merge sort is ideal for linked lists because:
- Finding the middle element is O(n) using slow-fast pointers
- Merging two sorted lists is O(n) and doesn't require extra space
- Overall complexity is O(n log n)
The algorithm:
- Find the middle of the list
- Recursively sort both halves
- Merge the two sorted halves
Algorithm
- Base case: If list has 0 or 1 nodes, return
- Find the middle using slow-fast pointer technique
- Split the list into two halves
- Recursively sort both halves
- Merge the sorted halves
Visualization
Input: 4 -> 2 -> 1 -> 3
Split:
4 -> 2 1 -> 3
| |
Split again Split again
4 2 1 3
| | | |
Merge Merge
2 -> 4 1 -> 3
| |
└───────┬───────┘
|
Final Merge
1 -> 2 -> 3 -> 4
Implementation
Complexity Analysis
- Time Complexity: O(n log n) - Divide and conquer
- Space Complexity: O(log n) - Recursive call stack
Bottom-Up Merge Sort (Iterative - O(1) Space)
Intuition
Instead of top-down recursion, we can use bottom-up approach:
- Start with sublists of size 1
- Merge adjacent sublists
- Double the size and repeat
This avoids recursive call stack.
Implementation
Complexity Analysis
- Time Complexity: O(n log n) - Same as recursive
- Space Complexity: O(1) - No recursion
Comparison with Array Merge Sort
| Aspect | Array | Linked List | |--------|-------|-------------| | Random Access | O(1) | O(n) | | Finding Middle | O(1) | O(n) | | Merge Extra Space | O(n) | O(1) | | Overall Space | O(n) | O(log n) or O(1) |
Key Takeaways
- Merge sort is ideal for linked lists due to efficient merging
- Finding middle uses the slow-fast pointer technique
- Start fast at
head.nextfor correct splitting - The merge step is the core operation - reusing nodes, no extra space
- Bottom-up approach achieves O(1) space by avoiding recursion
- This is a very important interview problem testing multiple concepts
- Time complexity is O(n log n) which is optimal for comparison-based sorting