Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.)
Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.)
def can_visit_all(rooms):
seen, st = {0}, [0]
while st:
for k in rooms[st.pop()]:
if k not in seen: seen.add(k); st.append(k)
return len(seen) == len(rooms), sorted(seen)
print(can_visit_all([[2], [3], [1], []]), can_visit_all([[1], [], [0, 1]]))What is printed?- A. (True, [0, 1, 2, 3]) (True, [0, 1, 2])
- B. (True, [0, 2, 1, 3]) (False, [0, 1])
- C. (True, [0, 1, 2, 3]) (False, [0, 1])
- D. (False, [0, 2]) (False, [0, 1])
Correct answer: C. (True, [0, 1, 2, 3]) (False, [0, 1])
Rooms are nodes and keys are directed edges; the question is whether everything is reachable from 0. First: 0 → 2 → 1 → 3, all four. Second: 0 → 1, and room 1 has no keys; room 2 (which has keys) is never opened. O(rooms + keys).
More Coding Interview Problems questions
- Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS…
- Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped. python import…
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…