Engineering platform~20 min2s · 256 MBtarget O(n) time, O(n) spacerecursion
A file-sync app stores folders as a tree. Folders are numbered 0 to n - 1, and folder 0 is the root. A list parents says which folder holds each folder.
Deeply nested folders slow the sync client, so the support team wants the depth of the deepest folder and how many folders sit at that depth. The natural way to write this is a recursive function, depth(folder) = 1 + the deepest child. A real folder tree can be a chain of 100,000 folders.
Write deepest_folder(parents).
parents[i] is the folder that holds folder i. The root is folder 0, and parents[0] = -1.[deepest, count]: the largest depth, and how many folders have exactly that depth.Input: parents = [-1, 0, 0, 1, 1, 2, 4]
Output: [4, 1]Take the tree with parents = [-1, 0, 0, 1, 1, 2, 4].
| Folder | Held by | Depth |
|---|---|---|
| 0 | none | 1 |
| 1 | 0 | 2 |
| 2 | 0 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 3 |
| 5 | 2 | 3 |
| 6 | 4 | 4 |
The deepest depth is 4, and only folder 6 has it. The answer is [4, 1].
Input: parents = [-1, 2, 0, 2, 3]
Output: [4, 1]Folder 1 is held by folder 2, which is held by folder 0. The depths are 1, 3, 2, 3 and 4, so the answer is [4, 1].
Input: parents = [-1, 0, 0, 1, 2]
Output: [3, 2]The depths are 1, 2, 2, 3 and 3. Two folders have the deepest depth 3, so the answer is [3, 2].
1 ≤ parents.length ≤ 100,000parents[0] = -1, and 0 ≤ parents[i] ≤ n - 1 for every other folderA tree with 100,000 folders can be one chain, so the deepest chain can hold 100,000 folders. A recursive depth would need 100,000 frames open at once. Python stops at about 1,000, and the default stacks of other languages can run out too. A loop with its own stack of folders has no such limit.