Ancestor traversal · Medium
A sitemap stores parent links rather than complete paths. The UI needs a breadcrumb for a selected page and must not loop on malformed links.
Return root-to-page IDs or null when the target is missing, a parent is missing or a cycle is encountered.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ pages: {id:string,parent:string|null}[], target:string }
Input rules
- IDs are unique.
What each field means
pages— records containing a pageidand its parent ID.parent: nullmarks a root.target— the page ID whose breadcrumb path is requested.
Output
Return value and rules
- Return IDs from the root to
target, including both. - Return
nullif the target is missing, an ancestor is missing, or the target’s ancestry contains a cycle. - An unrelated cycle elsewhere in
pagesmust not invalidate a valid target path.
Constraints
- 0 <= pages.length <= 100000; IDs have at most 40 ASCII characters
- Only the selected ancestry matters; unrelated cycles do not invalidate a valid path.
Examples
Example 1
{
"pages": [
{
"id": "a",
"parent": null
},
{
"id": "b",
"parent": "a"
}
],
"target": "b"
}Returns
[
"a",
"b"
]Example 2
{
"pages": [],
"target": "x"
}Returns
nullRequired complexity
O(n) time and O(n) space