Leetcode #882: Reachable Nodes In Subdivided Graph
In this guide, we solve Leetcode #882 Reachable Nodes In Subdivided Graph in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Graph, Shortest Path, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
Explanation: The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
Python Solution
class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
g = defaultdict(list)
for u, v, cnt in edges:
g[u].append((v, cnt + 1))
g[v].append((u, cnt + 1))
q = [(0, 0)]
dist = [0] + [inf] * n
while q:
d, u = heappop(q)
for v, cnt in g[u]:
if (t := d + cnt) < dist[v]:
dist[v] = t
q.append((t, v))
ans = sum(d <= maxMoves for d in dist)
for u, v, cnt in edges:
a = min(cnt, max(0, maxMoves - dist[u]))
b = min(cnt, max(0, maxMoves - dist[v]))
ans += min(cnt, a + b)
return ans
Complexity
The time complexity is O(n log n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.