Skip to content

Commit 9af563d

Browse files
committed
Adding Accepted Solution - Problem - 27 - Possible Bipartition
1 parent 90bc05c commit 9af563d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
##==================================
2+
## Leetcode May Challenge
3+
## Username: Vanditg
4+
## Year: 2020
5+
## Problem: 27
6+
## Problem Name: Possible Bipartition
7+
##===================================
8+
#
9+
#Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.
10+
#
11+
#Each person may dislike some other people, and they should not go into the same group.
12+
#
13+
#Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.
14+
#
15+
#Return true if and only if it is possible to split everyone into two groups in this way.
16+
#
17+
#Example 1:
18+
#
19+
#Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
20+
#Output: true
21+
#Explanation: group1 [1,4], group2 [2,3]
22+
#Example 2:
23+
#
24+
#Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
25+
#Output: false
26+
#Example 3:
27+
#
28+
#Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
29+
#Output: false
30+
class Solution:
31+
def possibleBipartition(self, N, dislikes):
32+
tmp = {}
33+
for dislike in dislikes:
34+
if dislike[0] in tmp:
35+
tmp[dislike[0]].add(dislike[1])
36+
else:
37+
tmp[dislike[0]] = set([dislike[1]])
38+
if dislike[1] in tmp:
39+
tmp[dislike[1]].add(dislike[0])
40+
else:
41+
tmp[dislike[1]] = set([dislike[0]])
42+
43+
lookup = {}
44+
for i in range(1, N+1):
45+
if i not in lookup:
46+
lookup[i] = 0
47+
stack = [i]
48+
while stack:
49+
a = stack.pop()
50+
if a in tmp:
51+
for b in tmp[a]:
52+
if b in lookup:
53+
if lookup[a] == lookup[b]:
54+
return False
55+
else:
56+
lookup[b] = (lookup[a]+1)%2
57+
stack.append(b)
58+
return True
59+

0 commit comments

Comments
 (0)