A-044● Day 442026.06.19hardleetcode #23neetcode150
Merge k Sorted Lists
#linked-list#divide-and-conquer#heap-priority-queue#merge-sort
01
Problem
· problemYou 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.
constraints
- · 0 ≤ k ≤ 10^4 (number of lists)
- · 0 ≤ lists[i].length ≤ 500 (per-list node count)
- · -10^4 ≤ lists[i][j] ≤ 10^4 (node values range)
- · Each list sorted in ascending order
- · Total nodes across all lists ≤ 10^4
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Does 'ascending order' mean smallest-to-largest for each linked list?
- ☐What if the input lists array is completely empty (k=0)?
- ☐Can individual lists be empty (e.g., lists = [[]])?
- ☐Can node values be negative?
- ☐What is the maximum total nodes across all lists?
- ☐Can the input lists contain cycles?
- ☐Should output be in descending order?
- ☐Can we modify the original input lists in-place?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Handle empty input
○
if not lists or len(lists) == 0:
○
if len(lists) == 0:
○
if lists:
step 2· Loop until one list remains
○
while len(lists) > 1:
○
while len(lists) > 0:
○
while len(lists) >= 1:
step 3· Iterate by step of 2│ nested
○
for i in range(0, len(lists), 2):
○
for i in range(0, len(lists)):
○
for i in range(len(lists)//2):
step 4· Handle odd count boundary│ │ nested
○
l2 = lists[i + 1] if (i + 1) < len(lists) else None
○
l2 = lists[i + 1]
○
l2 = lists[i + 1] if i + 1 < len(lists) - 1 else None
step 5· Append merged result│ │ nested
○
mergedLists.append(self.mergeList(l1, l2))
○
lists.append(self.mergeList(l1, l2))
○
mergedLists.extend([l1, l2])
step 6· Update for next round│ nested
○
lists = mergedLists
○
mergedLists = lists
○
lists.extend(mergedLists)
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[[1,4,5],[1,3,4],[2,6]]→
[1,1,2,3,4,4,5,6]
case 2
[]→
[]
case 3
[[]]→
[]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.