Problem Summary
This is a very important linked list + merge pattern problem.
You are given a linked list where:
Each bottom list is already sorted.
Your task:
Flatten everything into one sorted linked list using only bottom pointers
Key Insight
This is NOT a traversal problem.
This is a merge k-sorted linked lists problem.
Because:
Optimal Idea
We use divide and conquer (merge sort style):
Step 1
Flatten next list recursively
Step 2
Merge two sorted bottom-linked lists
Core Operation: Merge 2 Lists
We merge like:
Approach
Function 1:
flatten(root)
→ flatten(root.next)
→ merge(root, root.next)
Function 2:
merge(a, b)
→ sorted merge using bottom pointers
Example Intuition
5 → 10 → 19
↓ ↓ ↓
7 20 22
↓
8
Flatten step by step:
Java Solution
class Solution {
Node merge(Node a, Node b) {
Node dummy = new Node(0);
Node temp = dummy;
while (a != null && b != null) {
if (a.data < b.data) {
temp.bottom = a;
a = a.bottom;
} else {
temp.bottom = b;
b = b.bottom;
}
temp = temp.bottom;
}
if (a != null) temp.bottom = a;
else temp.bottom = b;
return dummy.bottom;
}
public Node flatten(Node root) {
if (root == null || root.next == null)
return root;
// flatten right side
root.next = flatten(root.next);
// merge current and right
root = merge(root, root.next);
return root;
}
}
Complexity
Key Takeaways
Pattern Recognition
If you see:
Think:
Merge K Sorted Lists Pattern
Summary
This problem demonstrates how to flatten a complex linked list structure by treating each vertical list as a sorted list and applying a divide-and-conquer merge strategy. By recursively flattening and merging, the entire structure is converted into a single sorted list using bottom pointers.