Critical Connections in a Network
Critical Connections in a Network is a hard graphs problem solved with the bfs / dfs basics pattern.
The best approach, optimal (same dfs with an explicit stack), runs in O(V + E) time and O(V + E) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (remove each link) up.
Problem
A data center has n servers numbered 0 to n - 1. They are joined by undirected network links given as connections, where connections[i] = [a, b] is a link between servers a and b. Using these links, every server can reach every other server, directly or through others.
A link is critical if removing it leaves some server unable to reach some other server. Return all critical links. You may return them in any order, and each link may be written as [a, b] or [b, a].
Examples
Example 1
- Input
n = 5, connections = [[0, 1], [1, 2], [2, 0], [1, 3], [3, 4]]- Output
[[1, 3], [3, 4]]- Why
- Servers 0, 1 and 2 form a loop, so any one of those links can fail and the loop still joins them. The links 1-3 and 3-4 have no backup: cutting either one cuts off server 4 (and server 3 too for 1-3).
Example 2
- Input
n = 2, connections = [[0, 1]]- Output
[[0, 1]]- Why
- The only link is the only path between the two servers.
Example 3
- Input
n = 4, connections = [[0, 1], [1, 2], [2, 3], [3, 0]]- Output
[]- Why
- The four servers sit on one ring. Removing any single link still leaves the rest of the ring as a path.
Constraints
2 <= n <= 10^5n - 1 <= connections.length <= 10^50 <= a, b <= n - 1anda != bfor each[a, b]- No link appears twice, and every server can reach every other one.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (remove each link) | O(E · (V + E)) | O(V + E) |
| DFS with discovery time and low value | O(V + E) | O(V + E) |
| Optimal (same DFS with an explicit stack) | O(V + E) | O(V + E) |
1Brute force (remove each link)
O(E · (V + E))One full BFS for each of the E links, and each BFS touches every server and link once.O(V + E)The adjacency list, the visited array and the BFS queue.Try the definition directly. For each link, pretend it is gone and run a BFS from server 0 over the other links. If some server can no longer be reached, that link was critical.
- Build an adjacency list where each entry also stores the index of its link.
- For each link index k: BFS from server 0, skipping link k.
- If the BFS visits fewer than n servers, add link k to the answer.
- Return all links found.
class Solution {
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int k = 0; k < connections.size(); k++) {
int a = connections.get(k).get(0), b = connections.get(k).get(1);
adj.get(a).add(new int[]{b, k});
adj.get(b).add(new int[]{a, k});
}
List<List<Integer>> result = new ArrayList<>();
for (int skip = 0; skip < connections.size(); skip++) {
boolean[] seen = new boolean[n];
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(0);
seen[0] = true;
int count = 1;
while (!queue.isEmpty()) {
int u = queue.poll();
for (int[] e : adj.get(u)) {
if (e[1] == skip || seen[e[0]]) continue;
seen[e[0]] = true;
count++;
queue.add(e[0]);
}
}
if (count < n) result.add(connections.get(skip));
}
return result;
}
}class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
adj = [[] for _ in range(n)]
for k, (a, b) in enumerate(connections):
adj[a].append((b, k))
adj[b].append((a, k))
result = []
for skip in range(len(connections)):
seen = [False] * n
seen[0] = True
queue = deque([0])
count = 1
while queue:
u = queue.popleft()
for v, k in adj[u]:
if k == skip or seen[v]:
continue
seen[v] = True
count += 1
queue.append(v)
if count < n:
result.append(connections[skip])
return resultclass Solution {
public:
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
vector<vector<pair<int, int>>> adj(n);
for (int k = 0; k < (int)connections.size(); k++) {
int a = connections[k][0], b = connections[k][1];
adj[a].push_back({b, k});
adj[b].push_back({a, k});
}
vector<vector<int>> result;
for (int skip = 0; skip < (int)connections.size(); skip++) {
vector<bool> seen(n, false);
queue<int> q;
q.push(0);
seen[0] = true;
int count = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto& [v, k] : adj[u]) {
if (k == skip || seen[v]) continue;
seen[v] = true;
count++;
q.push(v);
}
}
if (count < n) result.push_back(connections[skip]);
}
return result;
}
};function criticalConnections(n, connections) {
const adj = Array.from({ length: n }, () => []);
connections.forEach(([a, b], k) => {
adj[a].push([b, k]);
adj[b].push([a, k]);
});
const result = [];
for (let skip = 0; skip < connections.length; skip++) {
const seen = new Array(n).fill(false);
const queue = [0];
seen[0] = true;
let count = 1;
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
for (const [v, k] of adj[u]) {
if (k === skip || seen[v]) continue;
seen[v] = true;
count++;
queue.push(v);
}
}
if (count < n) result.push(connections[skip]);
}
return result;
}2DFS with discovery time and low value
O(V + E)Each server is entered once and each link is looked at twice, once from each end.O(V + E)The adjacency list, the tin and low arrays, and a recursion stack up to V deep.Run one DFS from server 0. Give each server a discovery time tin in the order it is first reached. Its low value is the smallest tin it can reach by going down its DFS subtree and then taking at most one link that jumps back up. For a tree link u to v, if low[v] > tin[u], nothing under v has a way back to u or above except this link, so it is a bridge. The parent link is skipped by its index so it is not mistaken for a way back.
- Build the adjacency list with link indexes. Set tin[] to -1 for every server.
- dfs(u, parentLink): set tin[u] = low[u] = timer++.
- For each (v, k) next to u with k != parentLink: if v is unvisited, call dfs(v, k), then low[u] = min(low[u], low[v]), and if low[v] > tin[u] record link k as critical.
- If v is already visited, it is an ancestor on a back link: low[u] = min(low[u], tin[v]).
- Call dfs(0, -1) and return the recorded links.
class Solution {
private List<List<int[]>> adj;
private int[] tin, low;
private int timer = 0;
private List<List<Integer>> result;
private List<List<Integer>> links;
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
links = connections;
adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int k = 0; k < connections.size(); k++) {
int a = connections.get(k).get(0), b = connections.get(k).get(1);
adj.get(a).add(new int[]{b, k});
adj.get(b).add(new int[]{a, k});
}
tin = new int[n];
low = new int[n];
Arrays.fill(tin, -1);
result = new ArrayList<>();
dfs(0, -1);
return result;
}
private void dfs(int u, int parentLink) {
tin[u] = low[u] = timer++;
for (int[] e : adj.get(u)) {
int v = e[0], k = e[1];
if (k == parentLink) continue;
if (tin[v] == -1) {
dfs(v, k);
low[u] = Math.min(low[u], low[v]);
if (low[v] > tin[u]) result.add(links.get(k));
} else {
low[u] = Math.min(low[u], tin[v]);
}
}
}
}class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
adj = [[] for _ in range(n)]
for k, (a, b) in enumerate(connections):
adj[a].append((b, k))
adj[b].append((a, k))
tin = [-1] * n
low = [0] * n
result = []
timer = 0
def dfs(u: int, parent_link: int) -> None:
nonlocal timer
tin[u] = low[u] = timer
timer += 1
for v, k in adj[u]:
if k == parent_link:
continue
if tin[v] == -1:
dfs(v, k)
low[u] = min(low[u], low[v])
if low[v] > tin[u]:
result.append(connections[k])
else:
low[u] = min(low[u], tin[v])
dfs(0, -1)
return resultclass Solution {
public:
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
adj.assign(n, {});
for (int k = 0; k < (int)connections.size(); k++) {
int a = connections[k][0], b = connections[k][1];
adj[a].push_back({b, k});
adj[b].push_back({a, k});
}
tin.assign(n, -1);
low.assign(n, 0);
timer = 0;
result.clear();
links = &connections;
dfs(0, -1);
return result;
}
private:
vector<vector<pair<int, int>>> adj;
vector<int> tin, low;
int timer = 0;
vector<vector<int>> result;
vector<vector<int>>* links = nullptr;
void dfs(int u, int parentLink) {
tin[u] = low[u] = timer++;
for (auto& [v, k] : adj[u]) {
if (k == parentLink) continue;
if (tin[v] == -1) {
dfs(v, k);
low[u] = min(low[u], low[v]);
if (low[v] > tin[u]) result.push_back((*links)[k]);
} else {
low[u] = min(low[u], tin[v]);
}
}
}
};function criticalConnections(n, connections) {
const adj = Array.from({ length: n }, () => []);
connections.forEach(([a, b], k) => {
adj[a].push([b, k]);
adj[b].push([a, k]);
});
const tin = new Array(n).fill(-1);
const low = new Array(n).fill(0);
const result = [];
let timer = 0;
function dfs(u, parentLink) {
tin[u] = low[u] = timer++;
for (const [v, k] of adj[u]) {
if (k === parentLink) continue;
if (tin[v] === -1) {
dfs(v, k);
low[u] = Math.min(low[u], low[v]);
if (low[v] > tin[u]) result.push(connections[k]);
} else {
low[u] = Math.min(low[u], tin[v]);
}
}
}
dfs(0, -1);
return result;
}3Optimal (same DFS with an explicit stack)
O(V + E)Each server is pushed and popped once, and each adjacency entry is read once.O(V + E)The adjacency list, tin, low, the position pointers and the explicit stack, all linear in size.The low-value DFS is the right algorithm, but a chain of 10^5 servers makes the recursion 10^5 calls deep, which can overflow the call stack. Keep your own stack instead. Each frame stores the server, the link used to enter it, and how far it has got through its adjacency list. When a frame finishes, pass its low value up to the parent and check the bridge rule there.
- Build the adjacency list with link indexes. Set tin[] to -1. Push server 0 with parent link -1 and give it tin = low = 0.
- Look at the top frame u. If it still has an unread neighbour (v, k): skip it when k is the entry link; if v is new, set tin[v] = low[v] = timer++ and push v with entry link k; otherwise low[u] = min(low[u], tin[v]).
- If u has no neighbours left, pop it. If a parent p remains on the stack: low[p] = min(low[p], low[u]), and if low[u] > tin[p] the entry link of u is critical.
- When the stack is empty, return the recorded links.
class Solution {
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int k = 0; k < connections.size(); k++) {
int a = connections.get(k).get(0), b = connections.get(k).get(1);
adj.get(a).add(new int[]{b, k});
adj.get(b).add(new int[]{a, k});
}
int[] tin = new int[n], low = new int[n], next = new int[n], entry = new int[n];
Arrays.fill(tin, -1);
List<List<Integer>> result = new ArrayList<>();
int[] stack = new int[n];
int top = 0, timer = 0;
stack[top++] = 0;
entry[0] = -1;
tin[0] = low[0] = timer++;
while (top > 0) {
int u = stack[top - 1];
if (next[u] < adj.get(u).size()) {
int[] e = adj.get(u).get(next[u]++);
int v = e[0], k = e[1];
if (k == entry[u]) continue;
if (tin[v] == -1) {
tin[v] = low[v] = timer++;
entry[v] = k;
stack[top++] = v;
} else {
low[u] = Math.min(low[u], tin[v]);
}
} else {
top--;
if (top > 0) {
int p = stack[top - 1];
low[p] = Math.min(low[p], low[u]);
if (low[u] > tin[p]) result.add(connections.get(entry[u]));
}
}
}
return result;
}
}class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
adj = [[] for _ in range(n)]
for k, (a, b) in enumerate(connections):
adj[a].append((b, k))
adj[b].append((a, k))
tin = [-1] * n
low = [0] * n
nxt = [0] * n
entry = [-1] * n
result = []
tin[0] = low[0] = 0
timer = 1
stack = [0]
while stack:
u = stack[-1]
if nxt[u] < len(adj[u]):
v, k = adj[u][nxt[u]]
nxt[u] += 1
if k == entry[u]:
continue
if tin[v] == -1:
tin[v] = low[v] = timer
timer += 1
entry[v] = k
stack.append(v)
else:
low[u] = min(low[u], tin[v])
else:
stack.pop()
if stack:
p = stack[-1]
low[p] = min(low[p], low[u])
if low[u] > tin[p]:
result.append(connections[entry[u]])
return resultclass Solution {
public:
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
vector<vector<pair<int, int>>> adj(n);
for (int k = 0; k < (int)connections.size(); k++) {
int a = connections[k][0], b = connections[k][1];
adj[a].push_back({b, k});
adj[b].push_back({a, k});
}
vector<int> tin(n, -1), low(n, 0), next(n, 0), entry(n, -1);
vector<vector<int>> result;
vector<int> stack;
int timer = 0;
stack.push_back(0);
tin[0] = low[0] = timer++;
while (!stack.empty()) {
int u = stack.back();
if (next[u] < (int)adj[u].size()) {
auto [v, k] = adj[u][next[u]++];
if (k == entry[u]) continue;
if (tin[v] == -1) {
tin[v] = low[v] = timer++;
entry[v] = k;
stack.push_back(v);
} else {
low[u] = min(low[u], tin[v]);
}
} else {
stack.pop_back();
if (!stack.empty()) {
int p = stack.back();
low[p] = min(low[p], low[u]);
if (low[u] > tin[p]) result.push_back(connections[entry[u]]);
}
}
}
return result;
}
};function criticalConnections(n, connections) {
const adj = Array.from({ length: n }, () => []);
connections.forEach(([a, b], k) => {
adj[a].push([b, k]);
adj[b].push([a, k]);
});
const tin = new Array(n).fill(-1);
const low = new Array(n).fill(0);
const next = new Array(n).fill(0);
const entry = new Array(n).fill(-1);
const result = [];
const stack = [0];
let timer = 0;
tin[0] = low[0] = timer++;
while (stack.length > 0) {
const u = stack[stack.length - 1];
if (next[u] < adj[u].length) {
const [v, k] = adj[u][next[u]++];
if (k === entry[u]) continue;
if (tin[v] === -1) {
tin[v] = low[v] = timer++;
entry[v] = k;
stack.push(v);
} else {
low[u] = Math.min(low[u], tin[v]);
}
} else {
stack.pop();
if (stack.length > 0) {
const p = stack[stack.length - 1];
low[p] = Math.min(low[p], low[u]);
if (low[u] > tin[p]) result.push(connections[entry[u]]);
}
}
}
return result;
}Edge cases to test
- A tree (exactly n - 1 links): every link is critical
- One big ring: no link is critical
- Two loops joined by a single link: only that link is critical
- A long chain of 10^5 servers, which breaks recursive code on the call stack
- Links written as [b, a] instead of [a, b]: the answer may list each pair in either order
Hints
Hint 1
A link is critical when it is not part of any loop. If it sits on a loop, the rest of the loop is a detour around it.
Hint 2
Run one DFS and number the servers in the order you first reach them. For each server, track the smallest number it can reach using its own subtree plus at most one back link.
Hint 3
For a tree link from u down to child v, if the smallest number reachable from v's subtree is still greater than u's number, nothing below v can get back to u or above without that link, so it is critical.
FAQ
What is the best time complexity for Critical Connections in a Network?
Optimal (same DFS with an explicit stack) runs in O(V + E) time and O(V + E) extra space. Each server is pushed and popped once, and each adjacency entry is read once.
Which pattern does Critical Connections in a Network use?
It is a graphs problem that uses the bfs / dfs basics pattern. Other problems with the same pattern: BFS - Normal + Level by Level, DFS - Recursive + Iterative, Clone Graph.
Is there a brute force solution for Critical Connections in a Network?
Yes. Brute force (remove each link) takes O(E · (V + E)) time and O(V + E) space. Try the definition directly.
Which edge cases should I test for Critical Connections in a Network?
A tree (exactly n - 1 links): every link is critical; One big ring: no link is critical; Two loops joined by a single link: only that link is critical; A long chain of 10^5 servers, which breaks recursive code on the call stack; Links written as [b, a] instead of [a, b]: the answer may list each pair in either order.