# Program to find mutual followers from a relations list in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

## Example

Let us see the following implementation to get better understanding

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

for a, b in relations:

if (b, a) in seen:

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

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

## Input

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


## Output

[0, 2]