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?- A. True True
- B. False False
- C. False True
- 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
- Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph. python from collections…
- Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8…
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…
- Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get…
- Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1…
- Problem: Count connected components of an undirected graph given as an edge list on n nodes. cpp int find(vector<int>& p, int x) { return…