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:

  1. Build the reference graph - Create connections between objects
  2. Mark phase - Starting from root objects, mark all reachable objects
  3. 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
INPUTALGORITHMRESULT123456ROOTObject Reference GraphRoot: 1, Unreachable: 5↔61MARK2345SWEEP6Mark-and-SweepPhase 1: Mark reachable (green)Phase 2: Sweep unmarked (red)Garbage[5, 6]Collected ObjectsObjects 5 and 6 are unreachablefrom root 1 and marked for GCKey Insight:Mark-and-sweep performs single traversal from roots to identify all reachable objects,making unreachable objects obvious by their absence of marks.TutorialsPoint - Garbage Collector Simulator | Mark-and-Sweep Algorithm
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen