## Uber Interview Question for Software Engineers

• 3

Country: United States
Interview Type: Phone Interview

Comment hidden because of low score. Click to expand.
2
of 2 vote

Typical topological sort that can be solved with DFS
Assume packages are nodes like this:

``````public List<Integer> installPackages(List<Node> packages) {

if(packages == null || packages.isEmpty()) return new LinkedList<Integer>();

int n = packages.size();
int[] parentsCount = new int[n];

for(Node package: packages) {
for(Node child: package.children) {
parentsCount[child.label]++;
}
}

List<Integer> sequence = new LinkedList<>(); //output to return
for(Node package: packages) {
dfs(sequence, parentsCount, package);
}

return sequence;
}

private void dfs(List<Integer> sequence, int[] parentsCount, Node package) {
if(parentsCount[package.label] == 0) {
parentsCount[package.label] --;
for(Node child: package.children) {
parentsCount[child.label]-- ;
dfs(sequence, parentsCount, child);
}
}
}``````

Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
We 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.

Comment hidden because of low score. Click to expand.
0
of 0 vote

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' ]``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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);

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;
}
}

}

static class Vertex {

private String id;

private Vertex parent;
private int distance = 0;
private Color color;

public Vertex(String id) {
this.id = id;

distance = 0;
color = Color.WHITE;
}
}

public static enum Color {
WHITE, GREY, BLACK;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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, s) }
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)
map.put(name, node)
}

return map[name] as Project
}

fun addEdge(startName: String, endName: String) {
val start = getOrCreateNode(startName)
val end = getOrCreateNode(endName)
}
}

class Project(val name: String) {
val children = ArrayList<Project>()
private val map = HashMap<String, Project>()
var state = State.BLANK

if (!map.containsKey(node.name)) {
map.put(node.name, node)
}
}

enum class State {
COMPLETE, PARTIAL, BLANK
}
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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:

for child in depGraph[newNode]:
queue.append(child)
out.append(child)

out.append(start)

return out

def retDepGraph():

visited = set()
out = []

for pac in given:
if pac in visited:
continue

#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()``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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:

for child in depGraph[newNode]:
queue.append(child)
out.append(child)

out.append(start)

return out

def retDepGraph():

visited = set()
out = []

for pac in given:
if pac in visited:
continue

#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()``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.