Data Structures & AlgorithmsModerateTCS NQT · graph warm-up
Problem: Is the graph with edges forming the 5-cycle 0-1-2-3-4-0 bipartite? And is the 4-cycle 0-1-2-3-0 bipartite? Run the BFS colouring code.
Problem: Is the graph with edges forming the 5-cycle 0-1-2-3-4-0 bipartite? And is the 4-cycle 0-1-2-3-0 bipartite? Run the BFS colouring code.
from collections import deque
def bip(n, edges):
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
col = [-1] * n
for s in range(n):
if col[s] != -1:
continue
col[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in g[u]:
if col[v] == -1:
col[v] = 1 - col[u]
q.append(v)
elif col[v] == col[u]:
return False
return True
print(bip(5, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]), bip(4, [(0, 1), (1, 2), (2, 3), (3, 0)]))What is printed?- A. True True
- B. True False
- C. False True
- D. False False
Correct answer: C. False True
An odd cycle of length 5 cannot be 2-coloured, so the first check fails. The even 4-cycle is bipartite.
More Coding Interview Problems questions
- Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code. python…
- Problem: Which statement about Fenwick (binary indexed) trees is false?
- Problem: Items have small values (at most 1000 each, n = 100) but very large weights (up to 10^9), and capacity W = 10^9. Which DP is…
- Problem: For n = 10^5 elements and q = 10^5 queries, a sqrt-decomposition answers each query in O(sqrt n). Roughly how many elementary…
- Problem: How many scalar multiplications does the naive product of a 3 x 4 matrix and a 4 x 2 matrix need?
- Problem: Using the cost of a spanning tree on the complete graph K4 (Cayley's formula n^(n-2)), how many spanning trees does K4 have?