P26 · 1 second · 256 MB
Subtree Sizes
You are given a tree on `n` nodes `0..n-1` as an undirected `edges` list. Root it at `root`. Return an array `size` where `size[v]` is the number of nodes in v's subtree, including v itself.
function subtreeSizes(n, edges, root) → number[]
CONSTRAINTS
- 1 ≤ n ≤ 400
- edges.length === n - 1
- The edges form a tree
- 0 ≤ root < n
Input: n = 4, edges = [[0,1],[0,2],[2,3]], root = 0
Output: [4, 1, 2, 1]
Input: n = 4, edges = [[0,1],[0,2],[2,3]], root = 2
Output: [2, 1, 4, 1]
Rooting at 2 puts 0 (and 1) under 2.
1
2
3
4
5
6
7
8
Arena judges JavaScript in a Web Worker (1s wall-clock, then TLE). Samples are public; submit runs hidden tests too. C++/Python is a later swarm package.