You are tasked with optimizing avatar load times for experiences on the Roblox platform.
Each avatar comprises multiple components (body parts, accessories, animations, etc.). Some components may depend on others (e.g., a specific hat can only be loaded after the head and hair).
Given a list of components and their dependencies, design an algorithm that determines the correct loading order for the avatar's components, ensuring all dependencies are respected. If multiple orderings exist, return the one preserving the relative order of the input. If circular or missing dependencies exist, return an error.
Input/Output Format
Input: a list of components and dependencies, expressed as multiple lists of strings. Each string list contains the component's name as the first element and is followed by an arbitrary number of strings representing dependent components.
Output: a list of components sorted by the order in which they need to be loaded, or a list with a single element "Error!" if no solution exists.
Example 1:
Input:
[
["Head"],
["Torso"],
["Legs"]
]
Output:
["Head", "Torso", "Legs"]
Explanation:
The 3 components don't have any dependency and therefore we can just return them in their original order.
Example 2:
Input:
[
["Hair","Head"],
["Hat","Hair"],
["Head"]
]
Output:
["Head", "Hair", "Hat"]
Explanation:
Hair is dependent on Head and therefore must be loaded after it. Hat is dependent on Hair and therefore must be loaded after it.
This suggests the ordering Head, Hair, Hat.
Example 3:
Input:
[
["Hair","Head"],
["Head","Hair"]
]
Output:
["Error!"]
Explanation:
Hair is dependent on Head and vice versa. Therefore no valid ordering exists and we return an error.
Example 4:
Input:
[
["Hair","Head"],
["Head"],
["Torso"],
["Arm","Torso"]
]
Output:
["Head", "Hair", "Torso", "Arm"]
Explanation:
Hair is dependent on Head and must come after it. Arm is dependent on Torso and must come after it. With only these constraints, multiple orders are possible (e.g. Head, Hair, Torso, Arm, or Torso, Arm, Head, Hair or even Head, Torso, Hair, Arm. However, since we must preserve the relative order of the input, the correct order is Head, Hair, Torso, Arm.