HARD NC#44 Blind #43 Linked List

23. Merge k Sorted Lists

๐Ÿ“– Problem

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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use divide and conquer strategy
  • โ†’ Pairwise merge lists in each iteration
  • โ†’ Keep reducing number of lists until only one remains
  • โ†’ Time: O(n log k) where n is total nodes, Space: O(1) excluding result

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse divide and conquer strategy
  • โ€ขPairwise merge lists in each iteration
  • โ€ขKeep reducing number of lists until only one remains

Common Pitfalls

  • โ€ขTime: O(n log k) where n is total nodes, Space: O(1) excluding result

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
mergeKLists([arrayToList([1,4,5]), arrayToList([1,3,4]), arrayToList([2,6])]);
Expected:
{"val":1,"next":{"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":4,"next":{"val":4,"next":{"val":5,"next":{"val":6,"next":null}}}}}}}}
Test Case 2
Not run
Input:
mergeKLists([]);
Expected:
null
Test Case 3
Not run
Input:
mergeKLists([arrayToList([])]);
Expected:
null

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit