0

I am solving this problem on hacker earth: https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/just-c3-has-ended-1/description/ . It clearly seems like a BFS Problem. I solved a few test cases but stuck on others due to time complexity issues. This is what I have done so far:


from collections import Counter
import queue


def solve(students, pairsmap):
    visited = Counter()
    maximum = 1
    pairs = 0
    for i in range(students):
        if(visited[i+1] == 0):
            visited[i+1] = 1
            pairs += 1
            count = bfs(students, i+1, visited, 1, pairsmap, maximum)
            maximum = count
    return pairs, maximum


def bfs(students, curr, visited, count, pairsmap, currMax):
    q = []
    q.append(curr)
    c = Counter()
    while q:
        element = q.pop()
        for k, v in pairsmap.items():
            if(k[0] == element and visited[k[1]] == 0):
                q.append(k[1])
                visited[k[1]] = 1
                count += 1
            elif (k[1] == element and visited[k[0]] == 0):
                q.append(k[0])
                visited[k[0]] = 1
                count += 1
            if currMax < count:
                currMax = count
    return currMax


students = input().split(" ")
n = int(students[0])
m = int(students[1])
pairsmap = Counter()
for i in range(m):
    pairs = input().split()
    # print(pairs)
    u = int(pairs[0])
    v = int(pairs[1])
    pairsmap[(u, v)] = 1
# print(pairsmap)
res = solve(n, pairsmap)
print(res[0], res[1])


Can anyone point towards an optimized or better approach?

Bismeet singh
  • 41
  • 1
  • 6

0 Answers0