Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Routes with an exact total weight

Medium · Target 20 minutes · Graphs

A weighted directed graph has n nodes numbered 0 to n − 1. Each triple [u, v, w] in edges is an edge from u to v of weight w; weights may be negative. Return the number of paths from source to destination that never repeat a node and whose weights add up to exactly target.

Examples

InputOutputWhy
n = 5, edges = [[0,1,2],[0,3,5],[1,4,2],[2,4,1],[3,2,2],[4,3,1]], source = 0, destination = 3, target = 520 → 3 (5) and 0 → 1 → 4 → 3 (2 + 2 + 1).
same graph, target = 70No route totals 7.
n = 3, edges = [[0,1,1],[1,2,1],[0,2,2]], source = 0, destination = 2, target = 22Both routes total 2.

Constraints

  • 2 ≤ n ≤ 12
  • 0 ≤ edges.length ≤ 40
  • −10 ≤ w ≤ 10
  • source ≠ destination

Hints

Hint 1

This asks about paths, not reachability, so a node may be used by several different paths: mark it only while it is on the current path.

Hint 2

Carry the running total down the recursion. At the destination, count the path if the total equals the target, then stop: a simple path cannot pass through the destination and come back.

Hint 3

Weights can be negative, so you cannot prune when the running total exceeds the target.

Where people lose marks

  • Continuing past the destination, which counts walks that leave it and return.
  • Pruning on the running total while weights can be negative.
  • Marking nodes visited for the whole search, which counts each node in at most one path.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.