Garbage Collector Simulator - Problem
You are tasked with implementing a mark-and-sweep garbage collector simulator. This is a fundamental memory management algorithm used in many programming languages.
Given a list of objects and their reference relationships, you need to:
- Build the reference graph - Create connections between objects
- Mark phase - Starting from root objects, mark all reachable objects
- Sweep phase - Collect (remove) all unmarked objects as garbage
Each object has an id and a list of references to other object IDs. Root objects are those that are directly accessible (not referenced by any other object or explicitly marked as roots).
Return the list of object IDs that should be garbage collected (unreachable objects).
Input & Output
Example 1 — Basic Garbage Collection
$
Input:
objects = [{"id":1,"references":[2,3]},{"id":2,"references":[4]},{"id":3,"references":[]},{"id":4,"references":[]},{"id":5,"references":[6]},{"id":6,"references":[5]}], roots = [1]
›
Output:
[5,6]
💡 Note:
Starting from root 1, we can reach objects 2, 3, and 4. Objects 5 and 6 form an isolated cycle and are unreachable from root 1, so they become garbage.
Example 2 — Multiple Roots
$
Input:
objects = [{"id":1,"references":[2]},{"id":2,"references":[]},{"id":3,"references":[4]},{"id":4,"references":[]}], roots = [1,3]
›
Output:
[]
💡 Note:
With roots 1 and 3, we can reach: from root 1 → object 2, from root 3 → object 4. All objects are reachable, so no garbage.
Example 3 — All Objects Unreachable
$
Input:
objects = [{"id":2,"references":[3]},{"id":3,"references":[]}], roots = [1]
›
Output:
[2,3]
💡 Note:
Root 1 doesn't exist in the object list, so objects 2 and 3 are unreachable and become garbage.
Constraints
- 1 ≤ objects.length ≤ 1000
- 1 ≤ object.id ≤ 10000
- 0 ≤ object.references.length ≤ 100
- 1 ≤ roots.length ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code