Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite).

Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite).
from collections import deque
def bip(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges: adj[u].append(v); adj[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 adj[u]:
                if col[v] == -1: col[v] = 1 - col[u]; q.append(v)
                elif col[v] == col[u]: return False
    return True
print(bip(4, [(0, 1), (1, 2), (2, 3), (3, 0)]), bip(5, [(0, 1), (1, 2), (2, 0), (3, 4)]))
What is printed?
  1. A. True True
  2. B. False False
  3. C. False True
  4. D. True False

Correct answer: D. True False

A graph is bipartite iff it has no odd cycle. The 4-cycle alternates colours; the triangle 0–1–2 forces two neighbours to share a colour. The outer loop over all s handles disconnected parts. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic