As per usual, in this blog post we will practice solving algorithms problems. And today our leetcode problem is: Merge k Sorted Lists.

Problem definition:

Merge k sorted linked lists and return it as one sorted list.



Output: 1->1->2->3->4->4->5->6

Two sorted lists

In case of the only two sorted lists we can use simple binary search with two pointers. Similarly like we did with Median of Two Sorted lists problem. But when we have 3 or more lists to iterate through it becomes a bit more complicated.

K Sorted lists

First let’s check how many lists we have in our input. It will help us determine how many pointers we need. In case of two lists we can just hardcode two pointers and it will work. But for an unknown number of lists we will need different way of keeping track of pointers and their positions.

Also we will have a problem growing complexity of comparison. In case of two lists we will need to do only one comparison operation, in case of 4 lists, 4 operations and so on. If we have 100 lists, it becomes a little less elegant to hard code conditions. We will need to come up with a smart way to compare all numbers at the same time.

#linked-lists #javascript #programming #computer-science #algorithms

Algorithms With JavaScript: Merge k Sorted Lists
3.55 GEEK