Flattening of LL
Pattern: Merging and sorting
Each top node starts a sorted column linked by child pointers. Flatten everything to the right first, then merge this column into the result along child pointers. The answer is one sorted chain of child pointers.
The problem
You are given a list whose nodes are linked by next. Each of those nodes also starts a sorted list going down through
child pointers. Flatten everything into one sorted list linked only by child pointers, with every next set to
null, and return its head. For example, columns 5 7 8 30, 10 20, 19 22 50 and 28 35 40 45 become
5 7 8 10 19 20 22 28 30 35 40 45 50.
The function name flattenLinkedList matches the takeUforward practice page. Use the link above for the exact
statement and limits. In this guide's code the second pointer is called child. The tests also check that no next
link is left on the result.
Think first
- Each column is sorted. Which earlier problem combines two sorted lists?
- How can you combine many columns using only that two-list step?
- Which pointer do you follow and set while merging here?
Hints
Brute force, and why it fails
Collect all values, sort, and build a new child chain: O(N log N) with new nodes. Merging columns one by one from the
right is O(N × k) for k columns of N nodes in total, and relinks the existing nodes. A heap of column heads (as in Merge
k Sorted Lists) gives O(N log k).
The key insight
Many sorted lists collapse into one by repeating a two-list merge. Recursion from the right gives a natural order for those merges.
Dry run
Four columns hang from the top list. Column 1 is 5 7 8 30, column 2 is 10 20, column 3 is 19 22 50, column 4 is 28 35 40 45.
The plan
function flatten(head):
if head is null or head.next is null: return head
rest = flatten(head.next)
head.next = null
return merge(head, rest) # merge along child pointers
function merge(a, b):
dummy, tail = new node
while a and b:
take the smaller of a and b, attach it to tail.child, advance it
tail.child = whichever of a, b is left
return dummy.child
Complexity
- Time
O(N × k)- Space
O(k)
Each of the k merges walks at most all N nodes. The recursion is k levels deep.
Edge cases
- One column: itself.
- Columns of one node each: a plain merge of single nodes.
- Columns of different lengths.
I've built my logic, show the code
Java
class Solution {
public ListNode flattenLinkedList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode rest = flattenLinkedList(head.next); // flatten everything to the right first
head.next = null;
return merge(head, rest); // then merge this column into it
}
private ListNode merge(ListNode a, ListNode b) { // merge two child chains
ListNode dummy = new ListNode(0), tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { tail.child = a; a = a.child; }
else { tail.child = b; b = b.child; }
tail = tail.child;
}
tail.child = a != null ? a : b;
return dummy.child;
}
}C++
class Solution {
public:
ListNode* flattenLinkedList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* rest = flattenLinkedList(head->next); // flatten everything to the right first
head->next = NULL;
return merge(head, rest); // then merge this column into it
}
ListNode* merge(ListNode* a, ListNode* b) { // merge two child chains
ListNode dummy(0);
ListNode* tail = &dummy;
while (a != NULL && b != NULL) {
if (a->val <= b->val) { tail->child = a; a = a->child; }
else { tail->child = b; b = b->child; }
tail = tail->child;
}
tail->child = a != NULL ? a : b;
return dummy.child;
}
};Python
from lib import ListNode
class Solution:
def flattenLinkedList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
rest = self.flattenLinkedList(head.next) # flatten everything to the right first
head.next = None
return self.merge(head, rest) # then merge this column into it
def merge(self, a: ListNode, b: ListNode) -> ListNode: # merge two child chains
dummy = tail = ListNode(0)
while a is not None and b is not None:
if a.val <= b.val:
tail.child, a = a, a.child
else:
tail.child, b = b, b.child
tail = tail.child
tail.child = a if a is not None else b
return dummy.childCommon mistakes
- Merging along
nextinstead ofchild. - Leaving
nextpointers on the result. - Recursing without cutting
head.next, which merges a column twice.