Implement Garbage Collector
You're given an object graph representing allocated objects in memory. Each object can reference other objects. The graph is represented as a JavaScript object where keys are object IDs, and values are arrays of IDs they reference.
You're also given a list of roots – objects that are considered accessible.
Your task is to simulate a garbage collector that removes any unreachable objects (not accessible from the root set) and returns the cleaned memory graph.
-
Input:
graph: an object representing the memory (e.g.,{ A: ['B'], B: ['C'], D: [] })roots: an array of root object IDs (e.g.,['A'])
-
Output:
- an object representing the cleaned graph containing only reachable objects.
Example Inputs & Outputs
// Example 1 Input: graph = { A: ['B'], B: ['C'], C: [], D: [] } roots = ['A'] Output: { A: ['B'], B: ['C'], C: [] } // Example 2 Input: graph = { A: ['B'], B: ['C'], D: ['E'], E: [] } roots = ['D'] Output: { D: ['E'], E: [] } // Example 3 Input: graph = { A: ['B'], B: [], C: [] } roots = ['A'] Output: { A: ['B'], B: [] }
Constraints & Edge Cases
- Each object ID is unique and used as a key in the input
graph. - If a root points to a non-existent key, it should be ignored safely.
- The graph can be cyclic, so cycles should not cause infinite loops.
- Empty roots → return an empty object.
- Empty graph → return an empty object.
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
