Skip to content

Commit 1da1fb7

Browse files
committed
Added c++ solution for 2000-2099 / 2097. Valid Arrangement of Pair
1 parent 966eae6 commit 1da1fb7

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <vector>
2+
#include <unordered_map>
3+
#include <stack>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
9+
unordered_map<int, stack<int>> graph;
10+
unordered_map<int, int> out_degree;
11+
12+
for (auto& p : pairs) {
13+
graph[p[0]].push(p[1]);
14+
out_degree[p[0]]++;
15+
out_degree[p[1]]--;
16+
}
17+
18+
int start = pairs[0][0];
19+
for (auto& [node, degree] : out_degree) {
20+
if (degree > 0) {
21+
start = node;
22+
break;
23+
}
24+
}
25+
26+
vector<vector<int>> result;
27+
stack<int> path;
28+
path.push(start);
29+
30+
while (!path.empty()) {
31+
int current = path.top();
32+
if (!graph[current].empty()) {
33+
path.push(graph[current].top());
34+
graph[current].pop();
35+
} else {
36+
if (path.size() > 1) {
37+
int end = path.top(); path.pop();
38+
result.push_back({path.top(), end});
39+
} else {
40+
path.pop();
41+
}
42+
}
43+
}
44+
45+
reverse(result.begin(), result.end());
46+
return result;
47+
}
48+
};

0 commit comments

Comments
 (0)