Find root IDs and paths
Problem: Find Root IDs and Paths
You are provided with a collection of string blocks. Each block is represented as a JSON object containing two fields: "id": string and "parentId": string | null.
A block is defined as a root if it satisfies either of the following conditions:
- Its
parentIdfield isnull. - Its
parentIdfield references an ID that does not exist within the entire collection of blocks.
Task 1: Find All Root IDs
Write a function that takes the collection of blocks as input and returns a list of all ids that correspond to root blocks.
Task 2: Find Path to Target ID (Follow-up)
Given a targetId (an id from one of the blocks), write a function that returns the ordered path of ids from its ultimate root block down to the targetId itself. The path should start with the root's id and end with the targetId's id.
Requirements
For both tasks, explain your chosen approach, detail the data structures you utilize, and provide a thorough analysis of the time and space complexity.
AI interview prep
Core dilemma
Efficiently identifying root nodes in a potentially disconnected graph with invalid parent references, and then traversing upwards to reconstruct a path, all while optimizing for time and space complexity.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Find root IDs and paths
Problem: Find Root IDs and Paths
You are provided with a collection of string blocks. Each block is represented as a JSON object containing two fields: "id": string and "parentId": string | null.
A block is defined as a root if it satisfies either of the following conditions:
- Its
parentIdfield isnull. - Its
parentIdfield references an ID that does not exist within the entire collection of blocks.
Task 1: Find All Root IDs
Write a function that takes the collection of blocks as input and returns a list of all ids that correspond to root blocks.
Task 2: Find Path to Target ID (Follow-up)
Given a targetId (an id from one of the blocks), write a function that returns the ordered path of ids from its ultimate root block down to the targetId itself. The path should start with the root's id and end with the targetId's id.
Requirements
For both tasks, explain your chosen approach, detail the data structures you utilize, and provide a thorough analysis of the time and space complexity.