- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of C++ from the credited upstream file 1192.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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>> criticalConnections(int n,4 vector<vector<int>>& connections) {5 vector<vector<int>> ans;6 vector<vector<int>> graph(n);7 8 for (const vector<int>& connection : connections) {9 const int u = connection[0];10 const int v = connection[1];11 graph[u].push_back(v);12 graph[v].push_back(u);13 }14 15 16 17 getRank(graph, 0, 0, vector<int>(n, NO_RANK), ans);18 return ans;19 }20 21 private:22 static constexpr int NO_RANK = -2;23 24 25 int getRank(const vector<vector<int>>& graph, int u, int currRank,26 vector<int>&& rank, vector<vector<int>>& ans) {27 if (rank[u] != NO_RANK) 28 return rank[u];29 30 rank[u] = currRank;31 int minRank = currRank;32 33 for (const int v : graph[u]) {34 35 if (rank[u] == rank.size() || rank[v] == currRank - 1)36 continue;37 const int nextRank =38 getRank(graph, v, currRank + 1, std::move(rank), ans);39 40 if (nextRank == currRank + 1)41 ans.push_back({u, v});42 minRank = min(minRank, nextRank);43 }44 45 rank[u] = rank.size(); 46 return minRank;47 }48};49