Question 51
MediumIn a directed acyclic graph, what is the fastest way to find single-source shortest paths?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
In a directed acyclic graph, what is the fastest way to find single-source shortest paths?
Bellman–Ford, in O(VE)
Dijkstra only
Floyd–Warshall
Relax edges in topological order, in O(V + E)
Sign up free to see the answer and a step-by-step explanation.
What does an articulation point (cut vertex) mean?
It has the highest degree
It is the root of the DFS tree
Removing it disconnects the graph
It is on every cycle
Sign up free to see the answer and a step-by-step explanation.
How many different topological orders does the DAG with edges A → C and B → C (and no others) have?
6
1
2
3
Sign up free to see the answer and a step-by-step explanation.
Which problem can be modelled with a graph and solved by BFS?
Reversing a string
Sorting numbers
Finding the median
Word ladder: the fewest one-letter changes from 'cold' to 'warm'
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
parent = list(range(5))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in [(0, 1), (1, 2), (3, 4)]:
parent[find(a)] = find(b)
print(len({find(x) for x in range(5)}))
4
3
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
g = {1: [2], 2: [3], 3: [1]}
state = {}
def has_cycle(u):
state[u] = 'grey'
for v in g[u]:
if state.get(v) == 'grey' or (v not in state and has_cycle(v)):
return True
state[u] = 'black'
return False
print(has_cycle(1))
False
Error
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
edges = sorted([(1, 0, 1), (2, 1, 2), (3, 2, 3), (4, 0, 2), (5, 1, 3)])
parent = list(range(4))
def find(x):
while parent[x] != x:
x = parent[x]
return x
total = 0
for w, a, b in edges:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
total += w
print(total)
7
5
Sign up free to see the answer and a step-by-step explanation.
Which algorithm finds the shortest paths between all pairs of vertices in O(V³)?
Floyd–Warshall
Prim
Kahn's algorithm
Dijkstra
Sign up free to see the answer and a step-by-step explanation.
How can you check whether an undirected graph is bipartite?
Try to 2-colour it with BFS or DFS; it is bipartite if no edge joins two vertices of the same colour
Check whether it is a tree
Check whether it has an even number of vertices
Count the edges
Sign up free to see the answer and a step-by-step explanation.
What does Kahn's algorithm for topological sorting use?
A queue of vertices with in-degree 0
A priority queue of edge weights
A hash of vertex names
A stack of visited vertices only
Sign up free to see the answer and a step-by-step explanation.
1
2
True
None
10
6