Number of Good Paths solution explained
Number of Good Paths is solved by adding tree nodes in increasing order of value and joining each one to neighbors whose value is no larger, using union-find. After all nodes with value v are joined, any component holding c nodes of value v contributes c × (c + 1) / 2 good paths, counting single nodes. Sorting dominates, so the whole thing runs in O(n log n) time.
By Evin JohnPublished 8 min read
The problem in plain terms
You have a tree with n nodes, numbered 0 to n - 1, a list of values with one value per node, and the list of edges. A path is good when its two end nodes have the same value and no node on the path, including the ends, has a larger value. A path of one node is good by this rule. A path and its reverse are the same path. Return how many good paths the tree has.
| Values | Edges | Good paths | Breakdown |
|---|---|---|---|
| [2, 1, 2, 3, 2] | 0-1, 1-2, 2-3, 3-4 | 6 | 5 singles + (0, 2); node 3 blocks paths to node 4 |
| [3, 1, 3, 3] | 0-1, 1-2, 1-3 | 7 | 4 singles + 3 pairs among nodes 0, 2, 3 through the small center |
| [1, 5, 1] | 0-1, 1-2 | 3 | Singles only; the 5 in the middle blocks 0 to 2 |
| [4, 4, 4] | 0-1, 1-2 | 6 | 3 singles + 3 pairs, equal values never block |
| [7] | none | 1 | One node, one path |
The first row shows both sides of the rule. Nodes 0 and 2 have value 2 and the node between them has value 1, so that path counts. Nodes 2 and 4 also have value 2, but node 3 with value 3 sits between them, so it does not. Before coding, confirm that equal values in the middle are allowed (they are, since the rule says no node is larger) and that single nodes count.
Why interviewers use it
It rewards one idea: process things in sorted order and let union-find grow components as a threshold rises. The same idea powers Kruskal's minimum spanning tree and many offline query problems. Interviewers use it to see whether you can move from a per-pair check to counting by component, and whether you can explain why each component's count is a simple formula.
Slow approach: explore under a cap from every node
For each node, run a search that is only allowed to step onto nodes whose value does not exceed the start node's value. Every node with the same value that the search reaches is the far end of a good path. To count each pair once, only count reached nodes with a larger index. Add n for the single-node paths.
def good_paths_slow(vals, edges):
n = len(vals)
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
total = n
for start in range(n):
cap = vals[start]
stack, seen = [start], {start}
while stack:
node = stack.pop()
for nxt in adj[node]:
if nxt not in seen and vals[nxt] <= cap:
seen.add(nxt)
stack.append(nxt)
if vals[nxt] == cap and nxt > start:
total += 1
return totalThis is correct because a tree has exactly one path between any two nodes. If a search capped at value v can reach a node, the unique path to it never exceeds v. It is also too slow: with tens of thousands of nodes, a search from every node is quadratic.
Main approach: grow components in value order
Turn the question around. Instead of starting from each node, raise a threshold from the smallest value upward. When the threshold reaches v, add every node with value v, and connect each one to any neighbor whose value is at most v. Neighbors with smaller values were added earlier, so they already sit in components. After this step, two nodes with value v are in the same component exactly when the path between them uses only values up to v, which is exactly the good path condition.
Now count. Group the value-v nodes by their component root. A component holding c of them gives c single-node paths and c × (c - 1) / 2 pairs, so c × (c + 1) / 2 in total. Nodes with the same value in different components are separated by something larger and contribute nothing together. Then move to the next value.
from collections import Counter, defaultdict
def good_paths(vals, edges):
n = len(vals)
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
parent = list(range(n))
def find(x):
root = x
while parent[root] != root:
root = parent[root]
while x != root:
nxt = parent[x]
parent[x] = root
x = nxt
return root
by_value = defaultdict(list)
for node, v in enumerate(vals):
by_value[v].append(node)
total = 0
for v in sorted(by_value):
group = by_value[v]
for node in group:
for nb in adj[node]:
if vals[nb] <= v:
ra, rb = find(node), find(nb)
if ra != rb:
parent[ra] = rb
for c in Counter(find(node) for node in group).values():
total += c * (c + 1) // 2
return totalfunction goodPaths(vals, edges) {
const n = vals.length;
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
adj[a].push(b);
adj[b].push(a);
}
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x) => {
let root = x;
while (parent[root] !== root) root = parent[root];
while (x !== root) {
const next = parent[x];
parent[x] = root;
x = next;
}
return root;
};
const byValue = new Map();
vals.forEach((v, node) => {
if (!byValue.has(v)) byValue.set(v, []);
byValue.get(v).push(node);
});
let total = 0;
for (const v of [...byValue.keys()].sort((a, b) => a - b)) {
const group = byValue.get(v);
for (const node of group) {
for (const nb of adj[node]) {
if (vals[nb] > v) continue;
const ra = find(node);
const rb = find(nb);
if (ra !== rb) parent[ra] = rb;
}
}
const perRoot = new Map();
for (const node of group) {
const r = find(node);
perRoot.set(r, (perRoot.get(r) || 0) + 1);
}
for (const c of perRoot.values()) total += (c * (c + 1)) / 2;
}
return total;
}Two details are easy to miss. First, finish all the unions for value v before you count, otherwise two value-v nodes joined through a later node of the same value get counted in separate groups. Second, the count must use find again after the unions, because roots change while you merge.
Trace on the star
Values [3, 1, 3, 3], center node 1. At threshold 1 only node 1 is added; it has no neighbor with value at most 1, so its component holds one node and adds 1. At threshold 3, nodes 0, 2 and 3 each join the center. All three now share a root, so c = 3 adds 3 × 4 / 2 = 6. The total is 7, matching the table.
Running time
| Approach | Time | Space | Comment |
|---|---|---|---|
| Check every pair's path directly | O(n³) naive, O(n²) with care | O(n) | Only as a starting point |
| Capped search from each node | O(n²) | O(n) | Correct, too slow for large trees |
| Sorted values plus union-find | O(n log n) | O(n) | Sorting and path-compressed finds are each O(n log n) or better |
Edge cases
- A single node: the answer is 1.
- All values equal: every pair is good, so the answer is n × (n + 1) / 2, which can exceed 32-bit range for large n.
- Strictly increasing values along a line: only the n single-node paths count.
- A high value in the center of a star: it blocks all pairs between leaves with lower values.
- Equal values separated by a larger one: they must land in different components when counted.
Common mistakes
- Sorting numbers in JavaScript with the default sort, which compares them as strings and puts 10 before 9.
- Counting pairs only, c × (c - 1) / 2, and forgetting the single-node paths.
- Counting after each individual union instead of after the whole value group.
- Joining a node to neighbors with larger values, which lets a forbidden node bridge two components.
- Using a recursive find on a long path-shaped tree without union by size, which can exceed recursion limits.
Explaining it clearly
Fictional example
- Candidate
- Checking every pair is quadratic at best. Since there is one path between any two nodes in a tree, a pair is good when both ends share a value v and they are connected using only nodes up to v.
- Candidate
- So I add nodes in increasing value order and union each with neighbors that are no larger. After finishing value v, each component with c nodes of value v gives c times c plus one over two good paths.
- Candidate
- Sorting is n log n, and with path compression the finds stay within that bound, so that is the overall cost.
Continue the set
For a gentler union-find warm-up, see Lexicographically Smallest Equivalent String. Remove Max Number of Edges to Keep Graph Fully Traversable uses two disjoint sets at once and a greedy order of edge types. Broader practice on trees and graphs is on the data structure interview questions page.
Natively for practice runs
While you rehearse, Natively can read a tree problem from a screenshot and propose an approach with code, useful as a check once you have reasoned through the threshold idea yourself. It transcribes the practice session on your computer, so you can later see whether you explained the c × (c + 1) / 2 count without stumbling. Read about an AI interview assistant for Mac and Windows.
Questions people ask
What is the efficient solution to Number of Good Paths?
Process nodes in increasing value order. Union each node with neighbors whose value is not larger, then for each value count how many of its nodes share a root; a group of c adds c × (c + 1) / 2.
Why does union-find work here?
A tree has one path between any two nodes. After merging everything up to value v, two value-v nodes share a component exactly when their path never exceeds v, which is the good path rule.
What is the time complexity?
O(n log n). Sorting the values dominates, and the union-find operations with path compression stay within that bound. Space is O(n).
Do single nodes count as good paths?
Yes. A one-node path has matching ends and no larger node, which is why each component adds c × (c + 1) / 2 and not just the pairs.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
