Uber Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
public class DependencyResolver {
public static void main(String[] args) {
Graph graph = new Graph(3);
graph.populateVertices(new String[] { "b", "a", "c" });
graph.createEdge("a", "b");
graph.createEdge("b", "c");
printDFS(graph);
}
private static void printDFS(Graph graph) {
Vertex[] verticies = graph.getVertices();
for (Vertex vertex : verticies) {
if (vertex.getColor() == Color.WHITE) {
callDFS(vertex);
}
}
}
private static void callDFS(Vertex vertex) {
vertex.setColor(Color.GREY);
List<Vertex> neighbours = vertex.getAdjacencyList();
for (Vertex neighbour : neighbours) {
if (neighbour.getColor() == Color.WHITE) {
neighbour.setParent(vertex);
callDFS(neighbour);
}
}
vertex.setColor(Color.BLACK);
System.out.println(vertex.getId());
}
}
class Graph {
private Vertex[] vertices = null;
public Graph(int size) {
vertices = new Vertex[size];
}
public void populateVertices(String[] vertexIDs) {
int count = 0;
for (String id : vertexIDs) {
Vertex vertex = new Vertex(id);
vertices[count++] = vertex;
}
}
public void createEdge(String start, String end) {
Vertex startNode = null;
Vertex endNode = null;
for (Vertex vertex : vertices) {
if (vertex.getId().equalsIgnoreCase(start)) {
startNode = vertex;
}
}
for (Vertex vertex : vertices) {
if (vertex.getId().equalsIgnoreCase(end)) {
endNode = vertex;
}
}
startNode.getAdjacencyList().add(endNode);
}
static class Vertex {
private String id;
private List<Vertex> adjacencyList;
private Vertex parent;
private int distance = 0;
private Color color;
public Vertex(String id) {
this.id = id;
adjacencyList = new ArrayList<Vertex>();
distance = 0;
color = Color.WHITE;
}
}
public static enum Color {
WHITE, GREY, BLACK;
}
}
Here is the solution in Kotlin, solved using depth-first traversal:
object Worksheet {
@JvmStatic fun main(args: Array<String>) {
val projects = arrayOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
val dependencies = arrayOf(arrayOf("a", "b"), arrayOf("b", "c"), arrayOf("a", "c"), arrayOf("d", "e"), arrayOf("b", "d"), arrayOf("e", "f"), arrayOf("a", "f"), arrayOf("h", "i"), arrayOf("h", "j"), arrayOf("i", "j"), arrayOf("g", "j"))
val buildOrder = buildOrderWrapper(projects, dependencies)
if (buildOrder.isEmpty()) {
println("Circular Dependency.")
} else {
for (s in buildOrder) {
println(s)
}
}
}
private fun buildOrderWrapper(projects: Array<String>, dependencies: Array<Array<String>>): Array<String> {
val graph = buildGraph(projects, dependencies)
val orderedProjects = Stack<Project>()
graph.nodes.forEach { p ->
if (!dfs(p, orderedProjects))
return emptyArray()
}
return Array(orderedProjects.size, { orderedProjects.pop().name })
}
private fun dfs(p: Project, orderedProjects: Stack<Project>): Boolean {
if (p.state == Project.State.PARTIAL)
return false
if (p.state == Project.State.BLANK) {
p.state = Project.State.PARTIAL
p.children.forEach { child ->
if (!dfs(child, orderedProjects)) {
return false
}
}
orderedProjects.push(p)
p.state = Project.State.COMPLETE
}
return true
}
private fun buildGraph(projects: Array<String>, dependencies: Array<Array<String>>): Graph {
val graph = Graph()
projects.forEach { s -> graph.getOrCreateNode(s) }
dependencies.forEach { s -> graph.addEdge(s[0], s[1]) }
return graph
}
class Graph {
val nodes = ArrayList<Project>()
private val map = HashMap<String, Project>()
fun getOrCreateNode(name: String): Project {
if (!map.containsKey(name)) {
val node = Project(name)
nodes.add(node)
map.put(name, node)
}
return map[name] as Project
}
fun addEdge(startName: String, endName: String) {
val start = getOrCreateNode(startName)
val end = getOrCreateNode(endName)
start.addNeighbor(end)
}
}
class Project(val name: String) {
val children = ArrayList<Project>()
private val map = HashMap<String, Project>()
var state = State.BLANK
fun addNeighbor(node: Project) {
if (!map.containsKey(node.name)) {
children.add(node)
map.put(node.name, node)
}
}
enum class State {
COMPLETE, PARTIAL, BLANK
}
}
}
Any valid topological sort of the graph will suffice.
function sort (G, vertex, visited, stack) {
var v = G.vertex(vertex)
var i = v.id()
visited[i] = true
var neighbors = v.neighbors()
for (var j = 0; j < neighbors.length; ++j) {
var w = G.vertex(neighbors[j])
if (!visited[w.id()]) {
sort (G, neighbors[j], visited, stack)
}
}
stack.push(vertex)
}
module.exports = function (G, vertex) {
var S = []
var visited = []
for (var i = 0; i < G.length; ++i) {
visited[i] = false
}
sort(G, vertex, visited, S)
return S
}
var G = [
[0, 1, 0, 0],
[0, 0, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
var vertexes = ['A', 'B', 'C', 'D']
G.vertex = function (v) {
var i = vertexes.indexOf(v)
return {
id: function () {
return i
},
neighbors: function () {
var neighbors = []
var row = G[i]
for (var j = 0; j < row.length; ++j) {
if (row[j]) {
neighbors.push(vertexes[j])
}
}
return neighbors
}
}
}
var solution = module.exports(G, 'A')
console.log(solution)
$ node topological-sort.js
[ 'C', 'D', 'B', 'A' ]
depGraph = {
"a" : [ "b" ],
"b" : [ "c" ],
"c" : [ 'e'],
'e' : [ ],
"d" : [ ],
"f" : ["e" , "d"]
}
given = [ "b", "c", "a", "d", "e", "f" ]
def retDeps(visited, start):
queue = []
out = []
queue.append(start)
while queue:
newNode = queue.pop(0)
if newNode not in visited:
visited.add(newNode)
for child in depGraph[newNode]:
queue.append(child)
out.append(child)
out.append(start)
return out
def retDepGraph():
visited = set()
out = []
# visited.add(given[0])
for pac in given:
if pac in visited:
continue
visited.add(pac)
#out.append(pac)
if pac in depGraph:
# find all children
for child in depGraph[pac]:
if child in visited:
continue
out.extend(retDeps(visited, child))
out.append(pac)
print(out)
retDepGraph()
depGraph = {
"a" : [ "b" ],
"b" : [ "c" ],
"c" : [ 'e'],
'e' : [ ],
"d" : [ ],
"f" : ["e" , "d"]
}
given = [ "b", "c", "a", "d", "e", "f" ]
def retDeps(visited, start):
queue = []
out = []
queue.append(start)
while queue:
newNode = queue.pop(0)
if newNode not in visited:
visited.add(newNode)
for child in depGraph[newNode]:
queue.append(child)
out.append(child)
out.append(start)
return out
def retDepGraph():
visited = set()
out = []
# visited.add(given[0])
for pac in given:
if pac in visited:
continue
visited.add(pac)
#out.append(pac)
if pac in depGraph:
# find all children
for child in depGraph[pac]:
if child in visited:
continue
out.extend(retDeps(visited, child))
out.append(pac)
print(out)
retDepGraph()
Typical topological sort that can be solved with DFS
Assume packages are nodes like this:
Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
- aonecoding January 15, 2017We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews. All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions.