MERGE k SORTED LISTS
An array of k linked-lists "lists", was given, of which each linked-list was sorted in ascending order. We were asked to merge all the linked-lists into one sorted linked-list and return it as shown in the given example below:
PROCEDURE
- I merged two lists at a time and pushed to the array until lists.length === 1 and returned into the array. For instance, if: x = 1 -> 4 -> 5 y = 1 -> 3 -> 4 mergedXY = 1 -> 1 -> 3 -> 4 -> 4 ->5
(push mergedXY to the array)
we now have lists = [2 -> 6
1 -> 1 -> 3 -> 4 -> 4 ->5]
(the merging was repeated again)
x = 2 -> 6
y = 1 -> 1 -> 3 -> 4 -> 4 ->5
mergedXY = 1 -> 1 -> 2-> 3 -> 4 -> 4 ->5 -> 6
(And this was pushed to the array)
lists = [1 -> 1 -> 2-> 3 -> 4 -> 4 ->5 -> 6]
- The above was returned.
CODE
var mergeKLists = function(lists) {
if(lists.length ===0){
return null;
}
while(lists.length>1){
let x = lists.shift();
let y = lists.shift();
let mergedXY = mergeList(x,y);
lists.push(mergedXY);
}
return lists[0]
};
OUTCOME
Top comments (0)