Asked inNagarro,SDE
Merge k sorted lists

Given 'K' sorted linked lists, each list is sorted in increasing order. You need to merge all these lists into one single sorted list. You need to return the head of the final linked list.

Input format:
The first line of input contains an integer 'T' denoting the number of queries or test cases. 

The first line of each test case consists of an integer 'K' denoting the number of lists.

Next 'K' lines for each test case will have space separated integers and ith line will have elements of the ith linked list separated by a single space and terminated by -1.
Output format:
For each test case, print a single line containing space-separated denoting the elements of the merged sorted list. The elements of the linked list must be separated by a single space and terminated by -1.

The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
0 <= K <= 10 ^ 3
0 <= length of lists <= 100
(-10 ^ 9) <= value of list elements <= (10 ^ 9) && value of list elements != -1.

Time limit: 1 sec.
CodingNinjas
author
2y

A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into the result in a sorted way...read more

CodingNinjas
author
2y
Compare one by one and find smallest
  1. The idea is to pick the nodes of the final list one by one, by comparing heads of all K lists.
  2. Pick the list with the smallest head value, add that node to the final...read more
CodingNinjas
author
2y
Naive Approach

Here we will perform a brute force of adding all the nodes in a separate list and then sort it.

  1. Traverse through all the linked lists and add each node in a different array.
  2. Sort the array...read more
CodingNinjas
author
2y
Using Priority Queue
  1. The idea is to use priority queue to reduce searching time for list with smaller head value.
  2. We will maintain a priority queue for the head node of K list.
  3. The top of the queue give...read more
Add answer anonymously...
Nagarro SDE Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter