1626. Widest Generation

Easy1.5 points estimatedTreeBreadth-First Search

A clan is drawn as an N-ary tree, with the founder at the root. Generation 1 is the root alone, generation 2 consists of the root's children, generation 3 of their children, and so on.

Given the root of the tree, return the 1-based number of the generation that contains the most nodes. If several generations share the largest size, return the smallest generation number among them.

Count each generation's size with a breadth-first traversal that processes the tree level by level. A leaf's children list may be empty or missing. A single-node tree answers 1. Target complexity: O(n) time, O(n) space.

Example 1

Input:
root = [1,null,3,2,4,null,5,6]
Output:
2
Explanation:

Level sizes are 1, 3, 2; the widest level is depth 2.

Example 2

Input:
root = [1,null,2,3,null,4,null,5]
Output:
2
Explanation:

Level 2 holds nodes 2 and 3, every other level holds one node, so depth 2 is the widest.

Example 3

Input:
root = [7]
Output:
1
Explanation:

A lone root forms the only level, so the answer is 1.

Constraints

1 ≤ nodes ≤ 1000

depth ≤ 1000

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…