Samanta  Moore

Samanta Moore

1629448020

How to "Merge k Sorted Lists" in Java Algorithms for Beginner

Task description:

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

A linked list is a data structure that consisted of nodes connected with each other by one(single linked list) of two(double linked list) pointers. Every node usually contains some value and pointer to the next node. The very first node is called Head and the last node is called Tail. Tail as a next pointer usually has null.


#Java 

What is GEEK

Buddha Community

How to "Merge k Sorted Lists" in Java Algorithms for Beginner
Samanta  Moore

Samanta Moore

1629448020

How to "Merge k Sorted Lists" in Java Algorithms for Beginner

Task description:

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

A linked list is a data structure that consisted of nodes connected with each other by one(single linked list) of two(double linked list) pointers. Every node usually contains some value and pointer to the next node. The very first node is called Head and the last node is called Tail. Tail as a next pointer usually has null.


#Java 

Edmond  Herzog

Edmond Herzog

1594685758

Algorithms With JavaScript: Merge k Sorted Lists

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.

Example:

Input:

[
1->4->5,
1->3->4,
2->6
]
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