Good evening! Here's our prompt for today.
You're given an array of multiple sorted linked lists. Can you write a method that returns it transformed into a single sorted linked list?

Each linked list can be represented as a series of nodes with the following definition:
1function Node(val) {
2 this.value = val;
3 this.next = null;
4}Here's how it would be invoked:
1// Input
2const arr = [
3 2 -> 6 -> 9,
4 1 -> 2 -> 7,
5 2 -> 6 -> 10
6]
7
8mergeLists(arr);
9
10// Output
111 -> 2 -> 2 -> 2 -> 6 -> 6 -> 7 -> 9 -> 10Constraints
- Each list can have up to
100000nodes - The cumulative sum of all the nodes in the linked lists will be <=
100000 - The values in the nodes will be in the range
-1000000000and1000000000 - Let
nandkbe the length of a linked list and number of lists - Expected time complexity :
O(n*k*log k) - Expected space complexity :
O(k)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx 'PASSED: Expect `mergeLists(2 -> 6 -> 9, 1 -> 2 -> 7, 2 -> 6 -> 10)` to return 1 -> 2 -> 2 -> 2 -> 6 -> 6 -> 7 -> 9 -> 10'var assert = require('assert');​function mergeLists(arrOfLists) { // fill in this method return [];}​// Supporting data structures​function Node(val) { this.val = val; this.next = null;}​class LinkedList { constructor() { this.head = null; this.tail = null; }​ prepend(newVal) { const currentHead = this.head; const newNode = new Node(newVal); newNode.next = currentHead; this.head = newNode;​ if (!this.tail) { this.tail = newNode; }Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

We'll now take you through what you need to know.
How do I use this guide?
This is a more difficult problem than it may initially seem!
An obvious brute force solution is simply to:
- Traverse through every list
- Store all the node values in an array
- Sort the array. Unfortunately here, the time complexity is O(n log n) since there are
ntotal nodes and sorting takesO(n log n)time.
We can improve on the brute force approach by instead comparing node to node, and putting them in the right order as we're traversing. This becomes very similar to the Merged Sorted Linked Lists problem.

A better approach is to introduce a data structure. We need something that is built to process and order elements one by one in an efficient manner. What about a priority queue?
A priority queue is an abstract data type used to maintain a queue, with each element having a concept of a priority or order to be served.
Let's start by implementing one with a simple insert method:
xxxxxxxxxxclass PriorityQueue { constructor() { this.first = null; this.size = 0; }​ insert(val) { // decide where in the queue it falls const newNode = new Node(val); // if there's no first node or this new node is higher priority, move it to first if (!this.first || newNode.val < this.first.val) { newNode.next = this.first; this.first = newNode; } else { // if it's a lower priority on the queue by value let currNode = this.first;​ // keep iterating until we find a node whose value we are greater than while (currNode.next && newNode.val > currNode.next.val) { currNode = currNode.next; } newNode.next = currNode.next; currNode.next = newNode; } }}Then, using it is a matter of running the linked lists through it:
xxxxxxxxxxlet pq = new PriorityQueue();for (let list of arrOfLists) { if (list) { let currentNode = list; pq.insert(currentNode.val);​ // process the rest of the list while (currentNode.next) { pq.insert(currentNode.next.val); currentNode = currentNode.next; } }}​// returning this will return the head of the priority queue linked list resultreturn pq.first || [];Don't forget to handle the case when the array is empty:
xxxxxxxxxxif (!arrOfLists || arrOfLists.length === 0) { return [];}Let's put it all together now.
One Pager Cheat Sheet
- You can merge multiple
sorted linked listsinto a single sorted linked list, with time complexity ofO(n*k*log k)and space complexity ofO(k). - We can improve the brute force solution to sorting a list of linked lists by introducing a
Priority Queuedata structure, which allows us to efficiently process and order elements one by one inO(n log n)time. - The process involves
runningthelinked liststhrough the designated software to achieve the desired result. - Always check for an empty array before attempting any operations.
Putting it all togetheris the key to achieving success.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx}var assert = require('assert');​function mergeLists(arrOfLists) { if (!arrOfLists || arrOfLists.length === 0) { return []; }​ let pq = new PriorityQueue(); for (let list of arrOfLists) { if (list) { let currentNode = list; pq.insert(currentNode.val);​ while (currentNode.next) { pq.insert(currentNode.next.val); currentNode = currentNode.next; } } } return pq.first || [];}​// Supporting data structures​class PriorityQueue { constructor() { this.first = null; this.size = 0; }​ insert(val) { const newNode = new Node(val);Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


