1630. Odd Subtree Count

Easy1.5 points estimatedTreeGraphDepth-First Search

A small village has n houses numbered 0 to n - 1, joined by n - 1 two-way footpaths so that every house can be reached from every other. The list edges holds the footpaths as pairs [u, v], in no particular order and with either endpoint first.

Treat house 0 as the entrance. The crowd of a house is the number of houses whose route to the entrance passes through it, counting the house itself, so the entrance has crowd n. Return how many houses have an odd crowd.

Aim for a single traversal: O(n) time and O(n) extra space.

Example 1

Input:
n = 5, edges = [[0,1],[0,2],[1,3],[1,4]]
Output:
5
Explanation:

The answer is 5. Crowds are 5, 3, 1, 1, 1, all odd.

Example 2

Input:
n = 4, edges = [[0,1],[1,2],[2,3]]
Output:
2
Explanation:

The answer is 2. Crowds along the path are 4, 3, 2, 1, so only two are odd.

Constraints

1 ≤ n ≤ 1000; edges.length == n - 1; edges form a tree on nodes 0..n-1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…