Flatten A Linked List
You are given a linked list containing N nodes, where every node in the linked list contains two pointers, first one is ‘NEXT’ which points to the next node in the list and the second one is ‘CHILD’ pointer to a linked list where the head is this node. And each of these child linked lists is in sorted order.
Your task is to flatten this linked such that all nodes appear in a single layer or level while the nodes should maintain the sorted order.
For example:
The given linked list is -
So your output should be
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 12 → 20 → null.
Note:
The flattened list will be printed using the bottom pointer instead of the next pointer.
The value of any node in the linked list will not be equal to -1.
Input format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of the test case contains ‘N’ which represents the number of next-nodes in the linked list.
The description of the next N lines is as follows-
Each line contains space-separated integers which are the child nodes of the head linked list and each line ends with -1 to indicate that the sublist is over. Thus, -1 will never be a linked list element.
Output format :
For each test case, return the head node of the final linked list. The output of each test case will be printed in a separate line.
Note:
You don’t have to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 100
1 <= C <= 20
1 <= data <= 1000
Time Limit: 1sec
CodingNinjas
author
2y
Brute Force
The idea is to use an extra array to first store all the elements of the linked list and then sort the array and finally put those elements back into the linked list and return.
- Declare an ...read more
CodingNinjas
author
2y
Using Priority Queue
The idea is to use the given situation that each sublist is sorted and there are a total of N nodes that means there are N sorted sublists. So the idea is to sort the whole thing.
...read more
CodingNinjas
author
2y
In-place
The idea is to merge the linked list in place and merge it recursively with the current flattened list. Basically, we are traversing through the linked list and each time, we are merging the t...read more
Add answer anonymously...
Top Morgan Stanley Technology Analyst interview questions & answers
Popular interview questions of Technology Analyst
Top HR questions asked in Morgan Stanley Technology Analyst
>
Morgan Stanley Technology Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app