Amazon | Onsite | Dublin | Social Graph

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-12-23Added By Anonymous
Source: Link

Company: Amazon
Role: unknown
Interview Stage: Onsite
Location: Dublin
Year: unknown

Original Post Content:

Given the social graph of a person, find all the nth connections of the person

The task is to find all the nth-level connections of a given person in a social graph. The graph is represented as an undirected graph where:

  • Each person (node) can have one or more direct connections (edges) to other people.
  • The graph is stored using an adjacency list.

The objective is to find all individuals who are at the nth degree of separation from a given person in the graph. The approach chosen to solve this problem is Breadth-First Search (BFS), which is ideal for exploring nodes level by level.

Approach:
The BFS algorithm explores the graph level by level starting from the source node (in this case, the given person). This ensures that we can accurately find all connections that are exactly n levels away from the source.

Solution Outline:
1. Initialize BFS:
2. Start from the given person (node).
3. Use a queue to store nodes to be explored, along with the current level (starting from 0 for the source node).
4. Maintain a visited set to avoid revisiting nodes and cycles.
5. Explore Nodes Level by Level

For each node, process its neighbors, and for each unvisited neighbor, enqueue it with the next level.
Stop once the queue reaches level n and collect all the nodes at level n.

After BFS completes, gather all nodes that are exactly n levels away from the source.

Comments