Program to find mutual followers from a relations list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list called relations. Where each element in relations list relations[i] contains two numbers [ai, bi] it indicates person ai is following bi on a social media platform. We have to find the list of people who follow someone and they follow them back, we have to return it in sorted sequence.

So, if the input is like relations = [[0, 2],[2, 3],[2, 0],[1, 0]], then the output will be [0, 2].

To solve this, we will follow these steps −

  • ans := a new set

  • seen := a new set

  • for each pair a and b in relations, do

    • mark pair (a, b) as seen

    • if (b, a) is also marked as seen, then

      • insert b and a into

  • sort the elements of ans and return


Let us see the following implementation to get better understanding

def solve(relations):
   ans = set()
   seen = set()

   for a, b in relations:
      seen.add((a, b))

      if (b, a) in seen:

   k = list(ans)
   rtr = sorted(k)
   return rtr

relations = [
   [0, 2],
   [2, 3],
   [2, 0],
   [1, 0]


[[0, 2],[2, 3],[2, 0],[1, 0]]


[0, 2]
Published on 12-Oct-2021 11:25:54