Find articulation points using DFS with discovery and low times. A vertex u is an articulation point if it has a child v with no back-edge from v or its descendants to an ancestor of u. Handle the special case for the DFS tree root.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a classic problem in graph theory - finding articulation points (also known as cut vertices) using DFS. An articulation point is a vertex whose removal increases the number of connected components in the graph.
The algorithm uses the concept of discovery time and low time:
discovery[u]: The time when vertex u is first visited
low[u]: The minimum discovery time reachable from the subtree rooted at u
Key observations:
For a non-root vertex u with parent p: u is an articulation point if there exists a child v such that low[v] >= discovery[u]. This means there's no back edge from v's subtree to an ancestor of u.
For the root vertex: It's an articulation point if it has two or more children in the DFS tree.
Let me write a comprehensive solution:
python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
self.time = 0
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected graph
def dfs_articulation_points(self, u, parent, visited, disc, low, articulation_points):
"""
DFS helper function to find articulation points
Args:
u: Current vertex
parent: Parent of u in DFS tree
visited: Array to track visited vertices
disc: Array to store discovery times
low: Array to store low values
articulation_points: Set to store articulation points
"""
visited[u] = True
discovery_children = 0
disc[u] = self.time
low[u] = self.time
self.time += 1
# Visit all adjacent vertices
for v in self.graph[u]:
if not visited[v]:
discovery_children += 1
self.dfs_articulation_points(v, u, visited, disc, low, articulation_points)
# Update low value of u based on the subtree rooted at v
low[u] = min(low[u], low[v])
# If u isn't the root and v's subtree can't reach back past u, then u is critical
if parent != -1 and low[v] >= disc[u]:
articulation_points.add(u)
elif v != parent:
# Back edge found - update low value
low[u] = min(low[u], disc[v])
# Root is an articulation point if it has multiple children in DFS tree
if parent == -1 and discovery_children > 1:
articulation_points.add(u)
The algorithm marks vertices as articulation points when either a non-root vertex has a child whose subtree contains no back edge to an ancestor, or when the root has multiple children in the DFS tree. Back edges are handled by updating the low value when encountering already-visited non-parent vertices. The test suite validates the articulation point detection across different graph structures. The first case checks a linear chain where vertices 1 and 3 serve as critical connection points. The second case verifies that a root node with multiple independent subtrees qualifies as an articulation point. The third case confirms that a fully connected cycle contains no articulation points since removing any single vertex still leaves the graph connected.
For more complex scenarios, a larger graph with 7 vertices tests multiple articulation points (1, 3, and 4) where each removal would disconnect portions of the graph. Finally, a disconnected graph with two separate components validates that articulation points are identified within each component independently, expecting vertices 1 and 4 as critical nodes in their respective subgraphs. low[u] = min(low[u], low[v])
print(f"{indent} Back from {v}: low[{u}]={low[u]}")
code
if parent != -1 and low[v] >= disc[u]:
print(f"{indent} ** ARTICULATION POINT: {u} (child {v} has low[{v}]={low[v]} >= disc[{u}]={disc[u]})")
articulation_points.add(u)
elif v != parent:
print(f"{indent} → Back edge: {u}-{v}")
low[u] = min(low[u], disc[v])
print(f"{indent} Update low[{u}]={low[u]} via back edge to {v}")
# Root is articulation point if it has 2+ children
if parent == -1 and children_count >= 2:
print(f"{indent}** ROOT ARTICULATION POINT: {u} (has {children_count} children)")
articulation_points.add(u)
The implementation continues the DFS traversal by updating the low values when returning from recursive calls and checking articulation point conditions. When a back edge is encountered, it updates the low value with the discovery time of the ancestor. The root node is marked as an articulation point only if it has two or more children in the DFS tree. d time and space complexity analysis:
python
def articulation_points_optimized(vertices, edges):
"""
Optimized version with inline comments explaining the algorithm
Time Complexity: O(V + E) where V is vertices and E is edges
Space Complexity: O(V) for the arrays and recursion stack
Args:
vertices: Number of vertices
edges: List of tuples (u, v) representing edges
Returns:
List of articulation points
"""
graph = [[] for _ in range(vertices)]
# Build adjacency list
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = [False] * vertices
disc = [-1] * vertices
low = [-1] * vertices
parent = [-1] * vertices
articulation_points = []
time = [0]
def dfs(u):
visited[u] = True
disc[u] = low[u] = time[0]
time[0] += 1
children = 0
for v in graph[u]:
if not visited[v]:
children += 1
parent[v] = u
dfs(v)
low[u] = min(low[u], low[v])
# Check if u is articulation point
if parent[u] == -1 and children > 1:
articulation_points.append(u)
elif parent[u] != -1 and low[v] >= disc[u]:
articulation_points.append(u)
elif v != parent[u]:
low[u] = min(low[u], disc[v])
for i in range(vertices):
if not visited[i]:
dfs(i)
return articulation_points
I'm building an adjacency list representation and initializing discovery and low-value arrays. The DFS traversal tracks discovery times and updates low values based on back edges, identifying articulation points when either a root has multiple children or a non-root vertex has a child whose subtree can't reach ancestors without going through it. "name": "Star graph",
"vertices": 5,
"edges": [(0, 1), (0, 2), (0, 3), (0, 4)],
"expected": [0]
},
{
"name": "Triangle (cycle)",
"vertices": 3,
"edges": [(0, 1), (1, 2), (2, 0)],
"expected": []
},
{
"name": "Bridge example",
"vertices": 4,
"edges": [(0, 1), (1, 2), (2, 3)],
"expected": [1, 2]
},
{
"name": "Complex graph",
"vertices": 7,
"edges": [(0, 1), (1
for i, test in enumerate(test_cases, 1):
result = articulation_points_optimized(test["vertices"], test["edges"])
status = "✓ PASS" if result == test["expected"] else "✗ FAIL"
print(f"Test {i}: {test['name']}")
print(f" Vertices: {test['vertices']}, Edges: {test['edges']}")
print(f" Expected: {test['expected']}")
print(f" Got: {result}")
print(f" Status: {status}\n")
I should build out a more thorough test suite to validate the algorithm across different graph structures and edge cases.
I'll create a class-based approach that encapsulates the articulation point detection logic. The key insight is using DFS to track discovery times and the lowest reachable vertex from each node's subtree. A vertex is an articulation point if removing it disconnects the graph—either it's the root with multiple children in the DFS tree, or it's a non-root vertex where some child's subtree can't reach back to an ancestor without going through it. The low value captures this by recording the minimum discovery time accessible from a vertex's descendants. ] >= discovery[u]:
articulation_points.add(u)
code
elif neighbor != parent:
low[u] = min(low[u], discovery[neighbor])
if parent == -1 and children > 1:
articulation_points.add(u)
def find(self) -> Set[int]:
"""
Find all articulation points
Returns:
Set of articulation point vertices
"""
visited = [False] * self.vertices
discovery = [0] * self.vertices
low = [0] * self.vertices
articulation_points = set()
self.time = 0
for vertex in range(self.vertices):
if not visited[vertex]:
self._dfs(vertex, -1, visited, discovery, low, articulation_points)
return articulation_points
The algorithm identifies articulation points by tracking discovery times and low values during DFS traversal. A vertex is an articulation point if it's the root with multiple children, or if a subtree cannot reach an ancestor without passing through it. Back edges update the low value to detect these connectivity constraints. ulation_points: List[int]) -> None:
"""Display graph structure and highlight articulation points"""
print(f"\nGraph with {vertices} vertices and {len(edges)} edges:")
print("Articulation Points:", artic_points if artic_points else "None")
code
# Create adjacency representation
adj = [[] for _ in range(vertices)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
print("\nAdjacency List:")
for i in range(vertices):
print(f" {i}: {adj[i]}")
The explanation continues by handling back edges and checking for articulation points at the root. When a vertex has multiple children in the DFS tree and is the root, it's marked as an articulation point. For non-root vertices, an articulation point is identified when a child's lowest reachable discovery time is greater than or equal to the current vertex's discovery time, indicating no back edge bypasses the current vertex. p1 = g1.find()
print(visualize_graph(5, edges1, ap1))
print(f"Articulation Points: {sorted(ap1)}")
print("Explanation: Removing vertex 1 or 3 disconnects the graph")
code
# Test Case 2
print("\n📊 Test Case 2: Root is Articulation Point")
print("-" * 40)
g2 = ArticulationPointsFinder(5)
edges2 = [(0, 1), (0, 2), (1, 3), (2, 4)]
for u, v in edges2:
g2.add_edge(u, v)
ap2 = g2.find()
print(visualize_graph(5, edges2, ap2))
print(f"Articulation Points: {sorted(ap2)}")
print("Explanation: Root (0) has 2 children in DFS tree")
# Test Case 3
print("\n📊 Test Case 3: Cycle (No Articulation Points)")
print("-" * 40)
g3 = ArticulationPointsFinder(3)
edges3 = [(0, 1), (1, 2), (2, 0)]
for u, v in edges3:
g3.add_edge(u, v)
ap3 = g3.find()
print(visualize_graph(3, edges3, ap3))
print(f"Articulation Points: {sorted(ap3)}")
print("Explanation: Cycle has no articulation points")
# Test Case 4 - Verbose
print("\n📊 Test Case 4: Complex Graph with Explanation")
print("-" * 40)
g4 = ArticulationPointsFinder(7)
edges4 = [(0, 1), (1, 2), (1, 3), (2, 3)]
edges4.extend([(3, 4), (4, 5), (5, 6), (6, 4)])
for u, v in edges4:
g4.add_edge(u, v)
ap4 = g4.find()
print(visualize_graph(7, edges4, ap4))
print(f"\nArticulation Points: {sorted(ap4)}")
print("\nDetailed DFS Traversal:")
g4.explain_path()
code
Key Concepts Explained
python
"""
ALGORITHM EXPLANATION:
1. DISCOVERY TIME (discovery[u]):
- Assigned when vertex u is first visited
- Increases monotonically: 0, 1, 2, ...
2. LOW VALUE (low[u]):
- Minimum discovery time reachable from subtree rooted at u
- Updated via:
a) Tree edges: low[u] = min(low[u], low[child])
b) Back edges: low[u] = min(low[u], discovery[ancestor])
3. ARTICULATION POINT CONDITIONS:
Condition 1 (Non-root vertex u with parent p):
─────────────────────────────────────────────
For child v: if low[v] >= discovery[u]
→ No back-edge from v's subtree to ancestor of u
→ Removal of u disconnects v from rest
Condition 2 (Root vertex):
─────────────────────────
If root has ≥ 2 children in DFS tree
→ Removal of root creates ≥ 2 components
4. TIME COMPLEXITY: O(V + E)
- Each vertex visited once
- Each edge traversed once
5. SPACE COMPLEXITY: O(V)
- Recursion stack: O(V) in worst case
- Arrays: O(V)
EXAMPLE:
0
|
1 ← ARTICULATION POINT
/ \
2 3 ← ARTICULATION POINT
|
4
- Removing vertex 1: {0} is separated
- Removing vertex 3: {4} is separated
"""
Output Example
code
Test 1: Simple Linear Chain
Graph: V=4, Edges=[(0, 1), (1, 2), (2, 3)]
Expected: [1, 2]
Got: [1, 2]
Status: ✓ PASS
DETAILED DFS TRAVERSAL:
→ Visit 0: disc[0]=0, low[0]=0
├─ Tree edge: 0→1
→ Visit 1: disc[1]=1, low[1]=1
├─ Tree edge: 1→2
→ Visit 2: disc[2]=2, low[2]=2
├─ Tree edge: 2→3
→ Visit 3: disc[3]=3, low[3]=3
← Leave 3: final low[3]=3
└─ Return from 3: low[2] = min(2, 3) = 2
⚠ ARTICULATION POINT 2: low[3]=3 >= disc[2]=2
← Leave 2: final low[2]=2
└─ Return from 2: low[1] = min(1, 2) = 1
⚠ ARTICULATION POINT 1: low[2]=2 >= disc[1]=1
← Leave 1: final low[1]=1
└─ Return from 1: low[0] = min(0, 1) = 0
← Leave 0: final low[0]=0