codekofi
← All problems

Problem 81

Hard

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Node {
2 int val;
3 Node* next;
4};
5
6Node* build(const vector<int>& values) {
7
8 Node stub{0, nullptr};
9 Node* tail = &stub;
10
11 for (int v : values) {
12 tail->next = new Node{v, nullptr};
13 tail = tail->next;
14 }
15
16 return stub.next;
17}
18
19vector<int> solution(const vector<vector<int>>& lists) {
20
21 vector<Node*> heads;
22
23 for (const auto& v : lists) {
24 heads.push_back(build(v));
25 }
26
27 using Item = pair<int, int>;
28 priority_queue<Item, vector<Item>, greater<Item>> live;
29
30 for (int i = 0; i < (int)heads.size(); i++) {
31 if (heads[i]) {
32 live.push({heads[i]->val, i});
33 }
34 }
35
36 vector<int> ans;
37
38 while (!live.empty()) {
39
40 auto [value, which] = live.top();
41 live.pop();
42
43 ans.push_back(value);
44
45 heads[which] = heads[which]->next;
46
47 if (heads[which]) {
48 live.push({heads[which]->val, which});
49 }
50 }
51
52 return ans;
53}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.