Bipartite Graph - Google Top Interview Questions
Problem Statement :
Given an undirected graph represented as an adjacency list, return whether the graph is bipartite. Constraints n, m ≤ 250 where n and m are the number of rows and columns in graph Example 1 Input graph = [ [1], [0] ] Output True Explanation This is bipartite since the node 1 can belong in set A and node 2 can belong in set B. Then the edges 0 - > 1 and 1 -> 0 has one node in A and one node in B Example 2 Input Visualize graph = [ [2, 3], [2, 3], [0, 1], [0, 1] ] Output True Explanation 0 and 1 can belong in set A and 2 and 3 can belong in set B. Example 3 Input graph = [ [1, 2, 3], [0, 2], [0, 1, 3], [0, 2] ] Output False Explanation No matter how the nodes are partitioned, an edge will belong to the same set.
Solution :
Solution in C++ :
bool isbipartite(vector<vector<int>> &graph, int src, vector<int> &color) {
for (int i = 0; i < graph[src].size(); i++) {
if (color[graph[src][i]] == -1) {
color[graph[src][i]] = !color[src];
if (!isbipartite(graph, graph[src][i], color)) return false;
} else if (color[graph[src][i]] == color[src])
return false;
}
return true;
}
bool solve(vector<vector<int>> &graph) {
// DFS by coloring nodes.
// Color root by R and subsequent by Blue if we found neighbour with same color it is not BPG.
vector<int> colors(graph.size(), -1);
for (int i = 0; i < graph.size(); i++) {
if (colors[i] == -1) {
colors[i] = 1;
if (!isbipartite(graph, i, colors)) return false;
}
}
return true;
}
Solution in Java :
import java.util.*;
class Solution {
private Set<Integer> visitedSet = new HashSet();
private Set<Integer> seta = new HashSet();
private Set<Integer> setb = new HashSet();
private boolean isBipartite = true;
public boolean solve(int[][] graph) {
if (graph == null || graph.length == 0)
return false;
for (int i = 0; i < graph.length; i++) {
if (!visitedSet.contains(i)) {
if (!isBipartite)
break;
;
dfs(graph, i, -1, 0);
}
}
return isBipartite;
}
private void dfs(int[][] graph, int vertex, int parent, int setIdentifier) {
addToSet(vertex, setIdentifier);
int[] adj = graph[vertex];
if (!isBipartite)
return;
for (int adjVertex : adj) {
if (adjVertex != parent) {
if (setIdentifier == 0 && seta.contains(adjVertex)) {
isBipartite = false;
return;
}
if (setIdentifier == 1 && setb.contains(adjVertex)) {
isBipartite = false;
return;
}
if (!seta.contains(adjVertex) && !setb.contains(adjVertex))
dfs(graph, adjVertex, vertex, (setIdentifier == 0 ? 1 : 0));
}
}
}
private void addToSet(int vertex, int setIdentifier) {
visitedSet.add(vertex);
if (setIdentifier == 0)
seta.add(vertex);
else
setb.add(vertex);
}
}
Solution in Python :
class Solution:
def solve(self, arr):
n = len(arr)
color_start = 1
seen = {}
def can_split(node, color):
if node in seen:
return seen[node]
seen[node] = color
for nei in arr[node]:
if nei not in seen:
if not can_split(nei, -color):
return False
elif seen[nei] != -color:
return False
return True
for i in range(n):
if not can_split(i, color_start):
return False
return True
View More Similar Problems
Delete duplicate-value nodes from a sorted linked list
This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -
View Solution →Cycle Detection
A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer
View Solution →Find Merge Point of Two Lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share
View Solution →Inserting a Node Into a Sorted Doubly Linked List
Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function
View Solution →Reverse a doubly linked list
This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.
View Solution →Tree: Preorder Traversal
Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's
View Solution →