codekofi
← All problems

Problem 63

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 vector<Node*> kin;
4};
5
6Node* copyOf(Node* node, unordered_map<Node*, Node*>& made) {
7
8 if (!node) {
9 return nullptr;
10 }
11
12 auto it = made.find(node);
13
14 if (it != made.end()) {
15 return it->second;
16 }
17
18 Node* fresh = new Node{node->val, {}};
19 made[node] = fresh;
20
21 for (Node* other : node->kin) {
22 fresh->kin.push_back(copyOf(other, made));
23 }
24
25 return fresh;
26}
27
28vector<vector<int>> solution(const vector<vector<int>>& links) {
29
30 int n = links.size();
31
32 if (n == 0) {
33 return {};
34 }
35
36 vector<Node*> nodes(n);
37
38 for (int i = 0; i < n; i++) {
39 nodes[i] = new Node{i + 1, {}};
40 }
41
42 for (int i = 0; i < n; i++) {
43 for (int j : links[i]) {
44 nodes[i]->kin.push_back(nodes[j - 1]);
45 }
46 }
47
48 unordered_map<Node*, Node*> made;
49 Node* copy = copyOf(nodes[0], made);
50
51 vector<vector<int>> ans(n);
52 vector<Node*> pending{copy};
53 set<int> seen;
54
55 while (!pending.empty()) {
56
57 Node* node = pending.back();
58 pending.pop_back();
59
60 if (seen.count(node->val)) {
61 continue;
62 }
63
64 seen.insert(node->val);
65
66 for (Node* other : node->kin) {
67 ans[node->val - 1].push_back(other->val);
68 pending.push_back(other);
69 }
70 }
71
72 return ans;
73}

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.