182k views
0 votes
Define a function which takes two parameters user_id and k and returns all users whom the user indicated by user_id knows by k steps away. For example:

1. k = 1, return all direct friends (immediately adjacent on the social graph) of the user_id

2. k = 2, return friends of direct friends of the user_id

3. k = 3, return friends of friends of direct friends of the user_id

4. so on..

User Merlo
by
9.1k points

1 Answer

4 votes

Final answer:

A function can be implemented using a graph data structure and a breadth-first search (BFS) algorithm to find users whom the user indicated by user_id knows by k steps away.

Step-by-step explanation:

The function can be implemented using a graph data structure and a breadth-first search (BFS) algorithm. Here is an example Python implementation:

from collections import deque
def find_friends(user_id, k):
# Construct the graph
graph = {
'user1': ['user2', 'user3'],
'user2': ['user1', 'user4'],
'user3': ['user1', 'user5'],
'user4': ['user2'],
'user5': ['user3']
}

# Perform BFS
queue = deque([(user_id, 0)])
visited = set([user_id])
friends = []

while queue:
current_user, steps = queue.popleft()

if steps == k:
break

for friend in graph[current_user]:
if friend not in visited:
visited.add(friend)
queue.append((friend, steps + 1))
friends.append(friend)

return friends
In this implementation, the graph represents the social graph where each key is a user and the value is a list of friends. The BFS algorithm is used to traverse the graph and find friends up to k steps away from the given user_id.

User Jeremy Rosenberg
by
8.4k points