Skip to content

Commit 9042cc9

Browse files
authored
Create 2097. Valid Arrangement of Pairs
1 parent 1e0caf8 commit 9042cc9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

2097. Valid Arrangement of Pairs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
4+
5+
vector<vector<int>> ans;
6+
unordered_map<int, int> mp;
7+
unordered_map<int, vector<int>> adj;
8+
9+
for (auto it : pairs) {
10+
mp[it[0]]++;
11+
mp[it[1]]--;
12+
adj[it[0]].push_back(it[1]);
13+
}
14+
15+
//finding start node
16+
int starting = pairs[0][0];
17+
for (auto it : mp) {
18+
if (it.second == 1) {
19+
starting = it.first;
20+
break;
21+
}
22+
}
23+
24+
vector<int> ref;
25+
stack<int> st;
26+
st.push(starting);
27+
//dfs
28+
while (st.size()) {
29+
auto& nodes = adj[st.top()];
30+
if (nodes.empty()) {
31+
ref.push_back(st.top());
32+
st.pop();
33+
} else {
34+
st.push(nodes.back());
35+
nodes.pop_back();
36+
}
37+
}
38+
// converting the path
39+
for (int i = ref.size() - 1; i > 0; i--) {
40+
ans.push_back({ref[i], ref[i - 1]});
41+
}
42+
43+
return ans;
44+
}
45+
};

0 commit comments

Comments
 (0)