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?- A. True True
- B. False False
- C. True False
- 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
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the…
- Problem: Count the ways to split s into a sequence of dictionary words. python def count(s, words): W = set(words); dp = [1] + [0] len(s)…
- Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match)…
- Problem: Count how many distinct index sequences of s spell t as a subsequence. python def distinct(s, t): dp = [1] + [0] len(t) for c in…
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…
- Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp). python INF…