Approach
Stack-based processing
For Valid Arrangement of Pairs, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 45 lines of C++ from the credited upstream file 2097.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {4 vector<vector<int>> ans;5 unordered_map<int, stack<int>> graph;6 unordered_map<int, int> outDegree;7 unordered_map<int, int> inDegrees;8 9 for (const vector<int>& pair : pairs) {10 const int start = pair[0];11 const int end = pair[1];12 graph[start].push(end);13 ++outDegree[start];14 ++inDegrees[end];15 }16 17 const int startNode = getStartNode(graph, outDegree, inDegrees, pairs);18 euler(graph, startNode, ans);19 ranges::reverse(ans);20 return ans;21 }22 23 private:24 int getStartNode(const unordered_map<int, stack<int>>& graph,25 unordered_map<int, int>& outDegree,26 unordered_map<int, int>& inDegrees,27 const vector<vector<int>>& pairs) {28 for (const auto& [u, _] : graph)29 if (outDegree[u] - inDegrees[u] == 1)30 return u;31 return pairs[0][0]; 32 }33 34 void euler(unordered_map<int, stack<int>>& graph, int u,35 vector<vector<int>>& ans) {36 auto& stack = graph[u];37 while (!stack.empty()) {38 const int v = stack.top();39 stack.pop();40 euler(graph, v, ans);41 ans.push_back({u, v});42 }43 }44};45