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?
  1. A. True True
  2. B. True False
  3. C. False True
  4. 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

Exams that ask this topic