Uber | Phone screen | USA
Company: Uber
Interview Stage: Phone screen
Location: USA
Original Post Content:
import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException; /* Let's write a simple mark-and-sweep garbage collector. 1. Mark phase: You're given a list of all "known alive" objects, or "roots". i.e. static objects, objects that are currently on the stack, etc. Given these root objects, you traverse the object graph to mark the objects that are reachable from any of them as "alive". Any object in the heap that cannot be reached by any of these roots are marked as "dead" in this phase. 2. Sweep phase: Go through all objects, if they are marked as "dead", free them. */ /* A a = new A(); B b = new B(); a.Field1 = b; a.Field2 = new C(); d = new D(); a --> b |---> c d If a is root, then b and c are alive. since b is alive, d is also alive. class A { static A SomeA; public B myB; public C myC; } public void someMethod() { A.SomeA = new A(); B myB = new B(); (alive) C myC = new C(); (alive) D myD = new D(); // this should be GC'd. A.SomeA.B = myB; A.SomeA.B.C = myC; myD.E = new E(); allObjects => {a, b, c, d, e} roots => {a} //a->a, b->a c->a // how many heap objects were allocated? => 4 return; // SomeA is the only thing we "know" to be alive. // SomeA has references to B and C fields. // SomeA ==> B; //. | ====> C; // } /* class A { static A SomeA; public B myB; public C myC; public void someMethod() { A.SomeA = new A(); B myB = new B(); C myC = new C(); D myD = new D(); // this should be GC'd. A.SomeA.B = myB; A.SomeA.B.C = myC; myD.E = new E(); } } class B { } class C { } class D { } */
class HeapObject { // an GC-internal representation of an object that's
// allocated on the heap. Object underlying; boolean isAlive;
// String name; List refs; public HeapObject(String name) {
// this.name = name; isAlive = true; refs = new ArrayList();
// } } // Main class should be named 'Solution' class
// Solution { public static void Mark(List allObjects, List
// roots) { // any objects in allObjects that cannot be
// reached by any of objects // in roots should be marked as
// isAlive = false; } //object -> parent public static void
// main(String[] args) { System.out.println("Hello, World");
// HeapObject a = new HeapObject("a"); HeapObject b = new
// HeapObject("b"); HeapObject c = new HeapObject("c");
// HeapObject d = new HeapObject("d"); a.refs.add(b);
// b.refs.add(c); List allObjects = new ArrayList<>(); List
// roots = new ArrayList<>(); allObjects.add(a);
// allObjects.add(b); allObjects.add(c); allObjects.add(d);
// roots.add(a); Mark(allObjects, roots); } }