Custom Garbage Collector - Problem

Design and implement a reference-counting garbage collector system that automatically manages object memory. Your implementation should:

1. Track references: Maintain reference counts for all objects

2. Detect zero references: Identify objects with no active references

3. Automatic cleanup: Free memory for unreferenced objects

4. Handle cycles: Deal with circular reference scenarios

Given a sequence of operations (create object, assign reference, remove reference), return the list of object IDs that should be garbage collected (freed from memory) at the end.

Operations:

CREATE id - Create new object with given ID

REF id1 id2 - Object id1 now references object id2

UNREF id1 id2 - Remove reference from id1 to id2

DELETE id - Delete object (remove from root set)

Input & Output

Example 1 — Basic Reference Tracking
$ Input: operations = ["CREATE A", "CREATE B", "REF A B", "DELETE A"]
Output: ["B"]
💡 Note: Create objects A and B. A references B (B's count = 1). Delete A removes the reference to B, making B's count = 0, so B becomes garbage.
Example 2 — Multiple References
$ Input: operations = ["CREATE X", "CREATE Y", "CREATE Z", "REF X Y", "REF Z Y", "DELETE X"]
Output: []
💡 Note: X and Z both reference Y (Y's count = 2). Deleting X reduces Y's count to 1, so Y is not garbage yet since Z still references it.
Example 3 — Circular References
$ Input: operations = ["CREATE P", "CREATE Q", "REF P Q", "REF Q P", "DELETE P", "DELETE Q"]
Output: ["P", "Q"]
💡 Note: P and Q reference each other. When both are deleted from root set, they still reference each other but are unreachable, so both become garbage.

Constraints

  • 1 ≤ operations.length ≤ 1000
  • Each object ID is a string of length 1-10
  • Operations are well-formed and valid
  • CREATE operations always use unique IDs

Visualization

Tap to expand
INPUT OPERATIONSREFERENCE TRACKINGGARBAGE COLLECTIONCREATE ACREATE BREF A BDELETE A1Track object creation2Update reference counts3Maintain object graph4Detect zero referencesARefs: 0BRefs: 0Objects with zeroreferences collectedKey Insight:Real-time reference counting eliminates the need for full system scans - objects are collected immediately when their reference count hits zero.TutorialsPoint - Custom Garbage Collector | Real-Time Reference Counting
Asked in
Google 25 Microsoft 20 Amazon 18 Apple 15
26.7K Views
Medium Frequency
~35 min Avg. Time
890 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