Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Heap

Merge K Sorted Lists

hard

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given k linked lists, each sorted in ascending order, in a list lists, write a function to merge the input lists into one sorted linked list.

Example 1:

Inputs:

lists = [[3,4,6],[2,3,5],[-1,6]]
3 -> 4 -> 6
2 -> 3 -> 5
-1 -> 6

Output:

[-1,2,3,3,4,5,6,6]

-1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 6

Explanation

This problem can be solved using a min-heap of size k.
The min-heap will always store the next unmerged element from each of the k sorted arrays. The element with the smallest value sits at the root of the heap. We build the merged array by repeatedly popping the root from the heap. Each time we pop from the heap, we also push the next element from the same array (if one exists) onto the heap.
When the heap is empty, all elements from all arrays have been merged, and we can return the merged result.

Step 1: Initialize the heap

The first step is to initialize the heap with the first element from each of the k arrays. We iterate over each array and push a tuple containing three values onto the heap:
  • The element's value
  • The array's index (which array it came from)
  • The element's index within that array (starting at 0)
Visualization
Python
Language
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-16

initialize heap

0 / 3

Step 2: Build the merged array

With the heap initialized, we can now build the merged result array. We start by creating an empty result array where we'll append elements in sorted order.
Visualization
Python
Language
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-16-1,2,03,0,02,1,0

add -1 to heap

0 / 1

Now, we repeatedly pop the root of the heap, which gives us the element with the smallest value among the unmerged elements from the k arrays. We append this value to our result array.
Visualization
Python
Language
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-16-1,2,03,0,02,1,00curr

initialize result array

0 / 1

To ensure that our heap always contains the next unmerged element from each array, after popping an element, we check if there's a next element in the same array. If there is, we push a tuple with the next element's value, the same array index, and the incremented element index onto the heap.
Visualization
Python
Language
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-162,1,03,0,00-1curr

add -1 to result

0 / 1

When the heap is empty, all elements from all arrays have been merged, and we can return the result array.
Visualization
Python
Language
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-160-12334566curr

add 6 to result

0 / 1

Solution

Visualization
Python
Language
Try these examples:
from heapq import heappush, heappop
def mergeKLists(lists):
if not lists:
return None
non_empty = [head for head in lists if head]
if not non_empty:
return None
heap = []
for head in non_empty:
heappush(heap, (head.val, id(head), head))
dummy = ListNode(0)
current = dummy
while heap:
val, _, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, id(node.next), node.next))
return dummy.next
346235-16

merge k sorted arrays

0 / 19

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n * log k) where n is the total number of elements across all input arrays and k is the number of arrays. We iterate over all elements from all arrays. At each iteration, we push and pop elements from the heap, which takes O(log k) time.

Space Complexity: O(k) where k is the number of arrays. We use a min-heap of size k to store the next unmerged element from each of the k arrays.

Mark as read

Next: Find Median from Data Stream

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsAnthropic SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress