918. Reachable Nodes In Subdivided Graph
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core of the problem is to find the number of nodes reachable from node 0 within a given number of moves (maxMoves). The graph is unique because edges are "subdivided," creating long chains of new nodes. The number of nodes in the subdivided graph can be enormous (up to n + 10^4 * 10^4), making it infeasible to build the graph explicitly and run a standard traversal algorithm like BFS or DFS.
Solution
Reachable Nodes In Subdivided Graph in Python
import heapq
class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
# Build adjacency list for the original graph.
# The weight of an edge is cnt + 1.
adj = [[] for _ in range(n)]
for u, v, cnt in edges:
adj[u].append((v, cnt + 1))
adj[v].append((u, cnt + 1))
# Dijkstra's algorithm to find shortest paths from node 0.
dist = [float('inf')] * n
dist[0] = 0
pq = [(0, 0)] # (distance, node)
while pq:
d, u = heapq.heappop(pq)
# If we've found a shorter path already, skip.
if d > dist[u]:
continue
for v, weight in adj[u]:
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(pq, (dist[v], v))
# Calculate total reachable nodes.
result = 0
# 1. Count reachable original nodes.
for i in range(n):
if dist[i] <= maxMoves:
result += 1
# 2. Count reachable subdivided nodes for each edge.
for u, v, cnt in edges:
# Moves left from u's side and v's side.
moves_u = max(0, maxMoves - dist[u]) if dist[u] != float('inf') else 0
moves_v = max(0, maxMoves - dist[v]) if dist[v] != float('inf') else 0
# The number of reachable new nodes is the sum of nodes reachable
# from both ends, capped by the total number of new nodes.
result += min(cnt, moves_u + moves_v)
return result
Reachable Nodes In Subdivided Graph in Java
class Solution {
public int reachableNodes(int[][] edges, int maxMoves, int n) {
// Adjacency list for the original graph. Stores [neighbor, weight].
// The weight of an edge is cnt + 1.
List<int[]>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int u = edge[0], v = edge[1], cnt = edge[2];
adj[u].add(new int[]{v, cnt + 1});
adj[v].add(new int[]{u, cnt + 1});
}
// Dijkstra's algorithm to find shortest paths from node 0.
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
// Priority queue stores {distance, node}.
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[]{0, 0});
while (!pq.isEmpty()) {
int[] curr = pq.poll();
int d = curr[0];
int u = curr[1];
if (d > dist[u]) {
continue;
}
for (int[] edge : adj[u]) {
int v = edge[0];
int weight = edge[1];
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.offer(new int[]{dist[v], v});
}
}
}
int result = 0;
// 1. Count reachable original nodes.
for (int i = 0; i < n; i++) {
if (dist[i] <= maxMoves) {
result++;
}
}
// 2. Count reachable subdivided nodes for each edge.
for (int[] edge : edges) {
int u = edge[0], v = edge[1], cnt = edge[2];
// Moves left from u's side and v's side.
long moves_u = (dist[u] > maxMoves) ? 0 : maxMoves - dist[u];
long moves_v = (dist[v] > maxMoves) ? 0 : maxMoves - dist[v];
// The number of reachable new nodes is the sum of nodes reachable
// from both ends, capped by the total number of new nodes.
result += Math.min(cnt, moves_u + moves_v);
}
return result;
}
}
Reachable Nodes In Subdivided Graph in C++
class Solution {
public:
int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {
// Build adjacency list for the original graph.
// The weight of an edge is cnt + 1.
vector<vector<pair<int, int>>> adj(n);
for (const auto& edge : edges) {
adj[edge[0]].push_back({edge[1], edge[2] + 1});
adj[edge[1]].push_back({edge[0], edge[2] + 1});
}
// Dijkstra's algorithm to find shortest paths from node 0.
vector<int> dist(n, INT_MAX);
dist[0] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, 0}); // {distance, node}
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
// If we've found a shorter path already, skip.
if (d > dist[u]) {
continue;
}
for (auto& edge : adj[u]) {
int v = edge.first;
int weight = edge.second;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
// Calculate total reachable nodes.
int result = 0;
// 1. Count reachable original nodes.
for (int i = 0; i < n; ++i) {
if (dist[i] <= maxMoves) {
result++;
}
}
// 2. Count reachable subdivided nodes for each edge.
for (const auto& edge : edges) {
int u = edge[0], v = edge[1], cnt = edge[2];
// Moves left from u's side and v's side.
long long moves_u = (dist[u] > maxMoves) ? 0 : maxMoves - dist[u];
long long moves_v = (dist[v] > maxMoves) ? 0 : maxMoves - dist[v];
// The number of reachable new nodes is the sum of nodes reachable
// from both ends, capped by the total number of new nodes.
// Use long long for the sum to prevent overflow.
result += min((long long)cnt, moves_u + moves_v);
}
return result;
}
};
Reachable Nodes In Subdivided Graph in TypeScript
function reachableNodes(edges: number[][], maxMoves: number, n: number): number {
// A Min-Priority Queue implementation for Dijkstra's algorithm
class MinPriorityQueue {
private heap: [number, number][] = [];
enqueue(element: [number, number]): void {
this.heap.push(element);
let i = this.heap.length - 1;
while (i > 0) {
const p = Math.floor((i - 1) / 2);
if (this.heap[p][0] > this.heap[i][0]) {
[this.heap[p], this.heap[i]] = [this.heap[i], this.heap[p]];
i = p;
} else {
break;
}
}
}
dequeue(): [number, number] | undefined {
if (this.isEmpty()) return undefined;
if (this.heap.length === 1) return this.heap.pop()!;
const root = this.heap[0];
this.heap[0] = this.heap.pop()!;
let i = 0;
while (true) {
const l = 2 * i + 1, r = 2 * i + 2;
let smallest = i;
if (l < this.heap.length && this.heap[l][0] < this.heap[smallest][0]) smallest = l;
if (r < this.heap.length && this.heap[r][0] < this.heap[smallest][0]) smallest = r;
if (smallest !== i) {
[this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
i = smallest;
} else {
break;
}
}
return root;
}
isEmpty(): boolean {
return this.heap.length === 0;
}
}
// Build adjacency list. Weight of an edge is cnt + 1.
const adj: [number, number][][] = Array.from({ length: n }, () => []);
for (const [u, v, cnt] of edges) {
adj[u].push([v, cnt + 1]);
adj[v].push([u, cnt + 1]);
}
// Dijkstra's algorithm from node 0.
const dist: number[] = new Array(n).fill(Infinity);
dist[0] = 0;
const pq = new MinPriorityQueue();
pq.enqueue([0, 0]); // [distance, node]
while (!pq.isEmpty()) {
const [d, u] = pq.dequeue()!;
if (d > dist[u]) {
continue;
}
for (const [v, weight] of adj[u]) {
if (dist[u] !== Infinity && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.enqueue([dist[v], v]);
}
}
}
let result = 0;
// 1. Count reachable original nodes.
for (let i = 0; i < n; i++) {
if (dist[i] <= maxMoves) {
result++;
}
}
// 2. Count reachable subdivided nodes.
for (const [u, v, cnt] of edges) {
const moves_u = dist[u] > maxMoves ? 0 : maxMoves - dist[u];
const moves_v = dist[v] > maxMoves ? 0 : maxMoves - dist[v];
result += Math.min(cnt, moves_u + moves_v);
}
return result;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.