KatInterview

Reachable Stocked Nodes Within a Hop Limit

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsbfsgraphsshortest-path

Last 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 nodes u and v. 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:

  1. The node is not target itself.
  2. Its value in stock is greater than zero.
  3. Its shortest-path distance to target (in hops) is at most radius.

The list may be returned in any order.

Notes

  • A node may appear in stock without having any edges in links, and a node may appear in links without appearing in stock.
  • A missing stock entry counts as zero and makes that node ineligible.
  • Duplicate edges and self-loops must not affect the result.
  • If radius is 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 <= radius
  • stock values 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.