Data Structures & AlgorithmsVery hardProduct company OA
BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)?
BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)?
from collections import deque
n = 9
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 4), (7, 8)]
adj = [[] for _ in range(n)]
for a, b in edges: adj[a].append(b); adj[b].append(a)
col = [-1] * n; bip = comps = 0
for s in range(n):
if col[s] != -1: continue
comps += 1; col[s] = 0; ok = True; q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if col[v] == -1: col[v] = col[u] ^ 1; q.append(v)
elif col[v] == col[u]: ok = False
bip += ok
print(comps, bip)- A. 3 3
- B. 4 2
- C. 3 1
- D. 3 2
Correct answer: D. 3 2
A component is bipartite iff it has no odd cycle; the BFS detects that as an edge joining two vertices of the same colour. Component {0, 1, 2, 3} is a 4-cycle (even → bipartite), {4, 5, 6} a triangle (odd → not), {7, 8} a single edge (bipartite). The colouring must restart in every uncoloured vertex, otherwise components are silently skipped. O(V + E).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…