Problem
Given a table GiftExchange
with columns person_id
and gift_to_id
, where each row represents a person giving a gift to another person, find all circular gift exchange chains. A circular chain is a sequence of people where each person gives a gift to the next, and the last person gives a gift to the first, with no repeats except the start/end.
Return all such chains as lists of person_ids, sorted in ascending order by the smallest person_id in each chain.
Example 1:
person_id | gift_to_id |
---|---|
1 | 2 |
2 | 3 |
3 | 1 |
4 | 5 |
5 | 4 |
Output:
|
|
Solution
Method 1 – Cycle Detection with Recursive CTE (SQL) and Graph Traversal (Pandas)
Intuition
A circular gift exchange is a cycle in a directed graph where each node (person) points to another node (gift recipient). We need to find all such cycles.
Approach
- For SQL (MySQL/PostgreSQL):
- Use a recursive CTE to traverse the gift chains starting from each person.
- Track the path and stop when a cycle is detected (the path returns to the start).
- Only output cycles where the start is the smallest id in the cycle to avoid duplicates.
- For Python (Pandas):
- Build a directed graph from the DataFrame.
- Use DFS to find all cycles, keeping track of visited nodes and paths.
- Normalize cycles to start from the smallest id and avoid duplicates.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, as each node may be visited in multiple paths for cycle detection. - 🧺 Space complexity:
O(n^2)
, for storing paths and cycles.