codekofi
← All problems

Problem 131

Medium

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 Node* extra;
5};
6
7Node* duplicate(Node* head) {
8
9 unordered_map<Node*, Node*> twin;
10
11 for (Node* p = head; p; p = p->next) {
12 twin[p] = new Node{p->val, nullptr, nullptr};
13 }
14
15 for (Node* p = head; p; p = p->next) {
16 twin[p]->next = twin[p->next];
17 twin[p]->extra = twin[p->extra];
18 }
19
20 return twin[head];
21}
22
23vector<pair<int, int>> solution(const vector<int>& values,
24 const vector<int>& links) {
25
26 int n = values.size();
27 vector<Node*> nodes(n);
28
29 for (int i = 0; i < n; i++) {
30 nodes[i] = new Node{values[i], nullptr, nullptr};
31 }
32
33 for (int i = 0; i < n; i++) {
34
35 if (i + 1 < n) {
36 nodes[i]->next = nodes[i + 1];
37 }
38
39 if (links[i] >= 0) {
40 nodes[i]->extra = nodes[links[i]];
41 }
42 }
43
44 Node* start = nullptr;
45
46 if (n) {
47 start = nodes[0];
48 }
49
50 Node* copy = duplicate(start);
51
52 unordered_map<Node*, int> where;
53 int k = 0;
54
55 for (Node* p = copy; p; p = p->next) {
56 where[p] = k;
57 k++;
58 }
59
60 vector<pair<int, int>> ans;
61
62 for (Node* p = copy; p; p = p->next) {
63
64 int link = -1;
65
66 if (p->extra) {
67 link = where[p->extra];
68 }
69
70 ans.push_back({p->val, link});
71 }
72
73 return ans;
74}

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.