Second round Phone interview (You tube ads team)
A social network
For e.g.
input: (a, b) , (c, d)
disjoint_set = {a,b}, {c,d}
For e.g.
input : (a, b) , (c, d) , (b, e)
disjoint_set = {a,b, e}, {c,d}
and so on
class social_network:
def __init__(self):
self.adj_list = {}
def input_friends(self, f1, f2):
if f1 not in self.adj_list:
self.adj_list[f1]=[]
self.adj_list[f1].append(f2)
if f2 not in self.adj_list:
self.adj_list[f2]=[]
self.adj_list[f2].append(f1)
def get_neighbors(self, node):
q=[node]
set_nodes=set()
while len(q)>0:
node = q.pop()
if node in set_nodes:
continue
set_nodes.add(node)
for neigh in self.adj_list[node]:
q.append(neigh)
return set_nodes
def find_disjoint_sets(self):
list_disjoint_sets=[]
for f1 in self.adj_list:
#check if that node is already in disjoint sets
flag_check = False
#check node exists in already added sets
for s_nodes in list_disjoint_sets:
if f1 in s_nodes:
flag_check=True
#if not is node in the already existing sets...then that becomes new disjoint set
if not flag_check:
set_nodes = self.get_neighbors(f1)
list_disjoint_sets.append(set_nodes)
return list_disjoint_sets
def main():
s_obj = social_network()
list_friends = [('a', 'b'), ('c', 'd'), ('a', 'e'), ('f', 'g'), ('g', 'h'), ('b', 'f'), ('d', 'i')]
for v in list_friends:
s_obj.input_friends(v[0], v[1])
disjoint_sets = s_obj.find_disjoint_sets()
print(disjoint_sets)
if __name__ == '__main__':
main()