Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Check whether each graph is bipartite with BFS 2-colouring (graphs may be disconnected).

Problem: Check whether each graph is bipartite with BFS 2-colouring (graphs may be disconnected).
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] = col[u] ^ 1; q.append(v)
                elif col[v] == col[u]: return False
    return True
print(bip(6, [(0,1),(1,2),(2,3),(3,0),(4,5)]), bip(7, [(0,1),(2,3),(3,4),(4,5),(5,6),(6,2)]))
What is printed?
  1. A. True True
  2. B. False False
  3. C. True False
  4. D. False True

Correct answer: C. True False

The first graph is a 4-cycle plus an edge: even cycles only, so bipartite. The second has the 5-cycle 2-3-4-5-6-2 in a separate component; an odd cycle forces two neighbours to share a colour. Starting BFS from every uncoloured node is what catches it.

More Coding Interview Problems questions

Exams that ask this topic