Asked inNagarro,SDE

Merge k Sorted Linked Lists

You are provided with 'K' sorted linked lists, each sorted in increasing order. Your task is to merge all these lists into one single sorted linked list and return the head of the resultant linked list.

Input:

The first line of input includes an integer 'T' representing the number of queries or test cases.

For each test case:
The first line contains an integer 'K', the number of lists.
The following 'K' lines contain integers, where each line represents the elements of each linked list, separated by a single space and ending with -1.

Output:

For every test case, provide a single line output containing the elements of the merged sorted list, separated by spaces and ending with -1.
The outputs for different test cases should be on separate lines.

Example:

Input:
T = 1
K = 3
1 4 5 -1
1 3 4 -1
2 6 -1
Output:
1 1 2 3 4 4 5 6 -1

Constraints:

  • 1 <= T <= 10
  • 0 <= K <= 103
  • 0 <= length of lists <= 100
  • -109 <= value of list elements <= 109 and value of list elements != -1
Note:
There is no need to print anything; just implement the function to return the required result.
AnswerBot
4mo

Merge k sorted linked lists into one single sorted linked list.

  • Create a min-heap to store the heads of all linked lists.

  • Pop the smallest element from the heap and add it to the result list.

  • If the popp...read more

Help your peers!
Select
Add answer anonymously...

Nagarro SDE interview questions & answers

A SDE was asked Q. Duplicate Subtrees Problem Statement Given a binary tree, return the root values...read more
A SDE was asked Q. Maximum Meetings Selection You are tasked with scheduling meetings in a single m...read more
A SDE was asked Q. Can you explain the concept of keys in database management systems?

Popular interview questions of SDE

A SDE was asked Q1. Duplicate Subtrees Problem Statement Given a binary tree, return the root values...read more
A SDE was asked Q2. Maximum Meetings Selection You are tasked with scheduling meetings in a single m...read more
A SDE was asked Q3. Can you explain the concept of keys in database management systems?
Nagarro SDE Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits