Reachable Stocked Nodes Within a Hop Limit
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests BFS on an undirected graph to filter nodes by shortest-path distance and a secondary inventory condition, including edge-case handling for missing keys and duplicates.
Reachable Stocked Nodes Within a Hop Limit
You are given an undirected network of nodes connected by bidirectional links. Each node may hold some quantity of stock. Given a target node and a distance budget, find every node that could supply stock to the target.
Input
links— a list of pairs[u, v], each representing a bidirectional edge between nodesuandv. Node IDs are integers. The list may be empty, may contain duplicate edges, and may contain self-loops.target— the integer ID of the destination node.radius— a nonnegative integer. The maximum number of hops allowed between a supplier and the target.stock— a mapping from node ID to stock quantity. A node absent from this mapping has an implied quantity of zero.
Output
Return a list of node IDs that satisfy all three conditions:
- The node is not
targetitself. - Its value in
stockis greater than zero. - Its shortest-path distance to
target(in hops) is at mostradius.
The list may be returned in any order.
Notes
- A node may appear in
stockwithout having any edges inlinks, and a node may appear inlinkswithout appearing instock. - A missing stock entry counts as zero and makes that node ineligible.
- Duplicate edges and self-loops must not affect the result.
- If
radiusis 0, the target itself is the only node at distance 0, and it is always excluded, so the result is always empty.
Constraints
0 <= len(links) <= 100 000- Node IDs are integers.
0 <= radiusstockvalues are integers; a value ≤ 0 means no usable stock.
Examples
Example 1
Input: reachable_stocked_nodes([[1, 2], [1, 3], [2, 4], [3, 4], [4, 5]], 4, 1, {'1': 2, '2': 0, '3': 5, '4': 3, '5': 6})
Output: []
Hints
Hint 1
Run a single BFS outward from the target node rather than launching a separate search from every stocked node — one traversal gives you the shortest distance to every reachable node at once.
Hint 2
Stop expanding a node as soon as its recorded distance equals the radius; its neighbors would be one hop further and are already out of range.
Hint 3
After the BFS, iterate over the stock mapping and apply all three eligibility checks — nodes that were never reached during BFS can be treated as having infinite distance.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to run a single BFS from the target rather than one BFS per stocked node. Because all edges are unweighted, BFS visits nodes in non-decreasing hop order, so the first time any node is reached its recorded distance is its true shortest-path distance. Reversing the direction works here because the graph is undirected: distance from X to target equals distance from target to X.
Step 1 — Build the adjacency list
Iterate over links once. For each pair [u, v], add each node to the other's neighbor list. Duplicate edges and self-loops are handled automatically: a duplicate just inserts a repeat entry, and the neighbor not in distances guard in the BFS skips it; a self-loop adds a node to its own list, which is also skipped once that node is already in distances.
Step 2 — Bounded BFS
Start from target at distance 0. When a node is dequeued, skip expanding it if its distance is already radius — its neighbors would be at radius + 1, which exceeds the budget. Any node that is never enqueued remains absent from distances.
Step 3 — Filter the stock mapping
Iterate over stock once. A node is eligible when:
- it is not
target, - its stock quantity is greater than zero,
distances.get(node, radius + 1) <= radius— the fallbackradius + 1correctly rejects nodes that are disconnected or unreachable.
The result list contains exactly those nodes.
Why It Is Correct
- BFS on an unweighted graph guarantees that the first recorded distance is the shortest-path distance.
- Stopping expansion at
radiuscannot lose any reachable node within the budget, because any such node lies on a path whose intermediate nodes are all at smaller distances and were therefore expanded. - Nodes that appear in
stockbut have no edges, or that are in a disconnected component, never enterdistancesand are rejected by the fallback default. - The destination node is always excluded regardless of its stock value.
Edge Cases
radius = 0: onlytargethas distance 0 and it is excluded, so the result is always[].- Stock values ≤ 0: rejected by the
qty > 0check. - Empty
links: no edges to traverse; onlytargetis indistances, so the result is[]. - Node IDs in
stockthat are not integers (e.g., string keys): they will never match integer keys indistances, so they are rejected — the behavior follows directly from the type mismatch.
Complexity
- Time: O(V + E) to build the adjacency list and run the BFS, plus O(|stock|) for the final filter. Overall O(V + E + |stock|).
- Space: O(V + E) for the adjacency list and the
distancesmap.
Reference Solution
from collections import deque
from typing import Dict, List
def reachable_stocked_nodes(links: List[List[int]], target: int, radius: int, stock: Dict) -> List[int]:
# Build adjacency list from the edge list.
graph = {}
for u, v in links:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
# BFS from the target to find shortest distances to all nodes within `radius` hops.
distances = {target: 0}
queue = deque([target])
while queue:
node = queue.popleft()
if distances[node] == radius:
# Neighbors would be at radius + 1, which is out of range.
continue
for neighbor in graph.get(node, ()):
if neighbor not in distances:
distances[neighbor] = distances[node] + 1
queue.append(neighbor)
# Collect nodes that pass all three eligibility checks.
return [
node for node, qty in stock.items()
if node != target
and qty > 0
and distances.get(node, radius + 1) <= radius
]