Flattening a Linked List | Practice | GeeksforGeeks

Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers:
(i) a next pointer to the next node,
(ii) a bottom pointer to a linked list where this node is head.
Each of the sub-linked-list is in sorted order.
Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. 
Note: The flattened list will be printed using the bottom pointer instead of next pointer.
 
Example 1:
Input:
5 -> 10 -> 19 -> 28
|     |     |     | 
7     20    22   35
|           |     | 
8          50    40
|                 | 
30               45
Output:  5-> 7-> 8- > 10 -> 19-> 20->
22-> 28-> 30-> 35-> 40-> 45-> 50.
Explanation:
The resultant linked lists has every 
node in a single level.
(Note: | represents the bottom pointer.)

 
Example 2:
Input:
5 -> 10 -> 19 -> 28
|          |                
7          22   
|          |                 
8          50 
|                           
30              
Output: 5->7->8->10->19->22->28->30->50
Explanation:
The resultant linked lists has every
node in a single level.

(Note: | represents the bottom pointer.)
 
Your Task:
You do not need to read input or print anything. Complete the function flatten() that takes the head of the linked list as input parameter and returns the head of flattened link list.
 
Expected Time Complexity: O(N*M*M)
Expected Auxiliary Space: O(1)
 
Constraints:
0 <= N <= 50
1 <= Mi <= 20
1 <= Element of linked list <= 103
0
rajparmar2380110 hours ago
JAVA Solution
 
class GfG
{
    ArrayList<Integer> al=new ArrayList<>();
    
    Node flatten(Node root)
    {
	// Your code here
	
	while(root!=null){
	    Node temp=root;
	    while(temp!=null){
            al.add(temp.data);
            temp=temp.bottom;
    }
	    root=root.next;
	}

    
    Collections.sort(al); 

    Node dummy=new Node(0);
    
    Node first_node=new Node(al.get(0));
    dummy.bottom=first_node;
    Node last=first_node;
    for(int i=1;i<al.size();i++){
  
        Node new_node=new Node(al.get(i));
    
        last.bottom=new_node;
        last=last.bottom;
    }
    return dummy.bottom;
    }
}
 
0
akshatjain231 day ago
Java - Explained - Easy Solution
 
class GfG
{
	Node flatten(Node root)
    {
        // If current sub list is null or it's last sub list
        // then there is nothing to flatten, return root.
	    if( root == null || root.next == null ) {
	        return root;
	    }
	    
	    // Flattening will be done from the end of the list 
	    // Keep calling flatten until we reach the second last sublist
	    Node nextSublistRoot = flatten( root.next );
	    
	    // Merge current sublist with the next sorted sublist
	    // using Merge Sort technique
	    return merge(root, nextSublistRoot);
    }
    
    Node merge(Node list1, Node list2) 
    {
        // We don't yet know which list's first node will going 
        // to be the head of the sorted list
        // Dummy node's bottom will point to the head of the merged list
        Node dummy = new Node(-1);
        
        // Pointer to the last merged node
	    Node tail = dummy;
	    
	    // Repeat until there are nodes in both the list
	    while( list1 != null && list2 != null ) {
	        
	        // Append the node to the bottom of the tail 
	        // from the list which has smaller value
	        if( list1.data > list2.data ) {
	            tail.bottom = list2;
	            list2 = list2.bottom;
	        } else {
	            tail.bottom = list1;
	            list1 = list1.bottom;
	        }
	        // Move pointer to latest merged node
	        tail = tail.bottom;
	    }
	    
	    // Merge list1 to the sorted list if list1 is not traversed completely
	    if( list1 != null ) {
	        tail.bottom = list1;
	    }
	    // Merge list2 to the sorted list if list2 is not traversed completely
	    if( list2 != null ) {
	        tail.bottom = list2;
	    }
	    
	    // Return head of merged list
	    return dummy.bottom;
    }
}
+2
prathamvaishya1231 week ago
public Node merge(Node fir, Node sec){       Node dummy = new Node(-1);       Node prev = dummy;       while(fir != null && sec != null){           if(fir.data < sec.data){               prev.bottom = fir;               prev = fir;               fir = fir.bottom;           }else {               prev.bottom =sec;               prev = sec;               sec = sec.bottom;           }                  }       while(fir != null){           prev.bottom = fir;           prev = fir;           fir = fir.bottom;       }       while(sec != null){           prev.bottom = sec;           prev = sec;           sec = sec.bottom;       }       return dummy.bottom;   }   Node flatten(Node root)   {       if(root == null || root.next == null) return root;    Node first = root;    Node sec = flatten(first.next);    return merge(first,sec);   }
0
vishalsavade2 weeks ago
//Easiest Way to Solve this problem
static bool cmp(Node *a, Node *b){
    return a->data < b->data;
}

Node *flatten(Node *root)
{
   vector<Node *> v;
   Node *t = root;
   while(t!=NULL){
       v.push_back(t);
       if(t->bottom != NULL){
           Node *p = t->bottom;
           while(p != NULL){
               v.push_back(p);
               p = p->bottom;
           }
       }
       t = t->next;
   }
   sort(v.begin(), v.end(), cmp);
    Node *q = new Node(0);
    Node *l = q;

  for(auto x: v){
      l->bottom = new Node(x->data);
      l = l->bottom;
  }
   return q->bottom;
}
//This code is contributed by Vishal Savade
 
0
harshscode2 weeks ago
Node* mergesort(Node *a,Node *b){   Node *ans;   if(!a)   return b;   else if(!b)   return a;      if(a->data<b->data)   {       ans=a;       ans->bottom=mergesort(a->bottom,b);   }   else    {       ans=b;       ans->bottom=mergesort(a,b->bottom);   }   ans->next=NULL;   return ans;}   Node *flatten(Node *root){  if(!root or !root->next)  return root;  return mergesort(root,flatten(root->next)); } 
0
deathcloud2 weeks ago
Easy Solution Using Merge
 
  
Node *merge(Node *first, Node *second){
    if(!second)
        return first;
    if(!first)
        return second;
    Node *p = first;
    Node *q = second;
    Node *prev = NULL;

    while(p && q){
        if(p->data <= q->data){
            prev = p;
            p = p->bottom;
        }else if(q->data < p->data){
            if(prev == NULL){
                Node *temp = q->bottom;   
                q->bottom = p;
                first = q;
                p = q;
                q= temp;
            }else{
                Node *temp = q->bottom;
                prev->bottom = q;
                q->bottom = p;
                prev = q;
                q = temp;
            }
        }
    }
    
    if(p == NULL){
        prev->bottom = q;
    }
        
    return first;
    
}

Node *flatten(Node *root)
{
   // Your code here
   Node *curr = root->next;
   while(curr){
       root = merge(root,curr);
       root->next = curr->next;
       curr = curr->next;
   }
   
   return root;
}


0
akshatdalmia0072 weeks ago
def flatten(root):   l = []   if not root:       return root   while root:       temp = root       l.append(root.data)              while root.bottom:           l.append(root.bottom.data)           root = root.bottom       temp = temp.next       root = temp   l.sort()   head = Node(l[0])   curr = t = head   for i in range(1,len(l)):       head = Node(l[i])       curr.bottom = head       curr = head   return t
0
tthakare732 weeks ago
//java Solution -> TC -> 0.64
// hint -> use priorityQueue
class GfG{
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    void triv(Node root){
        if(root == null){
            return;
        } 
        pq.add(new Integer(root.data));
        triv(root.bottom);
        triv(root.next);
    }
    
    Node flatten(Node root){
	    triv(root);
	    Node dummy = null;
	    while(!pq.isEmpty()){
	        int current = pq.poll();
	        Node newNode = new Node(current);
	        if(dummy == null){
	            root = newNode;
	            dummy = root;
	        } else {
	            dummy.bottom = newNode;
	            dummy = dummy.bottom;
	        }
	    }
	    return root;
    }
}
+1
adityagagtiwari3 weeks ago
Simple solution!
Time Complexity: O(N*M*M)Auxiliary Space: O(1)
class GfG
{
   Node flatten(Node root)
   {
// Your code here
if(root==null)
{
    return null;
}
    ArrayList<Node> list = new ArrayList<>();
    Node head = root;
    Node temp = root;
    Node resultant = null;
    while(head!=null)
    {
        resultant = mergeLL(head,resultant);
        head = head.next;
    }
    return resultant;
   }  
   Node mergeLL(Node head1,Node head2)
   {
       if(head2==null)
       return head1;
       if(head1==null)
       return head1;
       Node dummy = new Node(-1);
       Node temp = dummy;
       while(head1!=null && head2!=null)
       {
           if(head1.data<head2.data)
           {
               temp.bottom = head1;
               head1 = head1.bottom;
           }
           else
           {
               temp.bottom = head2;
               head2 = head2.bottom;
           }
       temp = temp.bottom;
       }
       if(head1!=null)
        temp.bottom = head1;
       if(head2!=null)
        temp.bottom = head2;
        
       return dummy.bottom;
   }
}
0
harshpandeyalfa23 weeks ago
C++
(0.01sec)
void add(Node* p , vector<int>& v){   while(p)   {       v.push_back(p->data);       p=p->bottom;   }}
Node *flatten(Node *root){  vector<int> v;  Node*it=root;  while(it)  {      v.push_back(it->data);      if(it->bottom)      {          add(it->bottom, v);      }      it=it->next;  } sort(v.begin(), v.end());    int i=0;  Node* head=new Node(v[i]);    it=head;  Node* s;  while(i < v.size()-1)  {      i++;      s=new Node(v[i]);      it->bottom=s;      it=s;  } return head;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.