Accenture · Question 56 · Heaps
Merge k Sorted Lists
Problem
Merge k sorted linked lists and return it as one sorted list.
Approach
Use a min - heap (priority queue) to efficiently get the smallest node among all lists.
Time O(Nlogk)Space O(k)
How it works
- 1Push every list head into a min-heap.
- 2Pop the smallest, append it, push its successor.
Sample input / output
Input: lists = [[1, 4, 5], [1, 3, 4], [2, 6]] Output: [1, 1, 2, 3, 4, 4, 5, 6]
Constraints
0 <= k <= 10^4; 0 <= total nodes <= 10^4.
Solution — read it, then walk it
Time O(Nlogk)Space O(k)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/26
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits