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
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output