← Accenture bank

Accenture · Question 56 · Heaps

Merge k Sorted Lists

HeapsC++code⏱ O(Nlogk)💾 O(k)
Service-based

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

  1. 1Push every list head into a min-heap.
  2. 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.
↻ repeatSTARTinclude <iostream>include <vector>include <queue>using namespace stdCLASS ListNodeDEFINE valListNode *nextListNode(int x) : val(x),next(nullptr) {}ListNode*buildList(std::initializer_list<int>vs)DEFINE printList(ListNode*head)cout << "["bool first = truewhile (head)if (!first) cout << ","first = falsecout << head->valhead = head->nextcout << "]" << endlCLASS Comparebool operator()(ListNode*a, ListNode* b)ListNode*mergeKLists(std::vector<ListNode*>&lists)DEFINE main()std::vector<ListNode*>lists = {buildList({1, 4,5}), buildList({1, 3, 4})…printList(mergeKLists(lists))RETURN 0END
  • 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