Facebook Pixel

Implement Garbage Collector

JavaScript
hard
25 mins

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:

intel
oracle
salesforce
phonepe

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.