I was doing k sorted linked list also at leetcode.
Question: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Question Link: https://leetcode.com/problems/merge-k-sorted-lists/submissions/
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Where Input of this
[[1,4,5],[1,3,4],[2,6]]
would actually look something like this (when passed)
[ ListNode { val: 1, next: ListNode { val: 4, next: [ListNode] } },
ListNode { val: 1, next: ListNode { val: 3, next: [ListNode] } },
ListNode { val: 2, next: ListNode { val: 6, next: null } } ]
So anyway, I wrote this code
// converts input array to object
const arrayToObject = (lists) => {
if (lists.length === 0) return lists
else {
let linkedListMergedArray = []
for (let i=0; i<lists.length; i++) {
const itterationItem = lists[i]
const reduceToArray = recursivelyCreateArray(itterationItem)
if (reduceToArray) linkedListMergedArray = [...linkedListMergedArray, ...reduceToArray ]
}
return linkedListMergedArray
}
}
// breaks down the object to linkedList
const recursivelyCreateArray = (listObject) => {
if (!listObject) return null
if (Array.isArray(listObject)) return arrayToObject(listObject)
if (!listObject.next) return [listObject.val]
else return [listObject.val, ...recursivelyCreateArray(listObject.next)]
}
// creates an object which looks like { val: value, next { val: value
const convertMergedArrayToOutputLinkedList = (mergedArray, i=0) => {
if (!mergedArray[i]) return null
else return {
val: mergedArray[i],
next: convertMergedArrayToLinkedList(mergedArray, i+1)
}
}
//starting point of code
var mergeKLists = function(lists) {
const linkedListToArray = arrayToObject(lists)
if (linkedListToArray.length > 0) {
const sortArray = linkedListToArray.sort((a,b) => a-b)
return convertMergedArrayToOutputLinkedList(sortArray)
} else return null
};
But this is failing for following input
[[0,2,5]]
while, I am still debugging it, I have a feeling that this isn't optimal algo so can someone please help me in writing an optimised code and also, In figuring out what I could be doing wrong?
1and other values more than once?1->1->2->3->4->4->5->6