Skip to content

Commit

Permalink
Updated
Browse files Browse the repository at this point in the history
  • Loading branch information
jeantimex committed Jun 9, 2018
1 parent b264d91 commit fabc1ac
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion src/linked-list/merge-k-sorted-lists.js
Expand Up @@ -31,7 +31,54 @@
* @return {ListNode}
*/
const mergeKLists = lists => {

if (!lists || lists.length === 0) {
return null;
}

const merge = (a, b) => {
if (!a || !b) {
return a || b;
}

let result;

if (a.val < b.val) {
result = a;
result.next = merge(a.next, b);
} else {
result = b;
result.next = merge(a, b.next);
}

return result;
};

const helper = (arr, last) => {
// repeat until only one list is left
while (last !== 0) {
let i = 0,
j = last;

// (i, j) forms a pair
while (i < j) {
// merge List i with List j and store
// merged list in List i
arr[i] = merge(arr[i], arr[j]);

// consider next pair
i++, j--;

// if all pairs are merged, update last
if (i >= j) {
last = j;
}
}
}

return lists[0];
};

return helper(lists, lists.length - 1);
};

export { mergeKLists };

0 comments on commit fabc1ac

Please sign in to comment.