Program to find mutual followers from a relations list in Python

Suppose we have a list called relations, where each element relations[i] contains two numbers [ai, bi] indicating that person ai is following bi on a social media platform. We need to find mutual followers − people who follow someone and are followed back by them. The result should be returned in sorted order.

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

Algorithm

To solve this, we will follow these steps −

  • Create a set to store mutual followers

  • Create a set to track all seen relationships

  • For each relationship [a, b] in the relations list:

    • Add the relationship (a, b) to the seen set

    • Check if the reverse relationship (b, a) already exists in seen

    • If yes, add both a and b to the mutual followers set

  • Convert the set to a sorted list and return

Example

Let us see the following implementation to get better understanding ?

def solve(relations):
    mutual_followers = set()
    seen = set()
    
    for a, b in relations:
        seen.add((a, b))
        
        if (b, a) in seen:
            mutual_followers.add(a)
            mutual_followers.add(b)
    
    return sorted(list(mutual_followers))

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

print(solve(relations))

The output of the above code is ?

[0, 2]

How It Works

In this example:

  • [0, 2]: Person 0 follows person 2

  • [2, 3]: Person 2 follows person 3

  • [2, 0]: Person 2 follows person 0 (mutual with the first relationship)

  • [1, 0]: Person 1 follows person 0

Since we have both (0, 2) and (2, 0) relationships, persons 0 and 2 are mutual followers.

Alternative Approach Using Dictionary

We can also solve this using a dictionary to count relationships ?

def solve_with_dict(relations):
    from collections import defaultdict
    
    following = defaultdict(set)
    mutual_followers = set()
    
    for a, b in relations:
        following[a].add(b)
        
        # Check if b follows a back
        if a in following[b]:
            mutual_followers.add(a)
            mutual_followers.add(b)
    
    return sorted(list(mutual_followers))

relations = [[0, 2], [2, 3], [2, 0], [1, 0]]
print(solve_with_dict(relations))
[0, 2]

Conclusion

Both approaches efficiently find mutual followers by tracking relationships in a set or dictionary. The set-based approach is simpler and has O(n) time complexity where n is the number of relationships.

Updated on: 2026-03-26T15:52:56+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements