Problem
Table: SecretSanta
|
|
Write a solution to find the total gift value and length of circular chains of Secret Santa gift exchanges:
A circular chain is defined as a series of exchanges where:
- Each employee gives a gift to exactly one other employee.
- Each employee receives a gift from exactly one other employee.
- The exchanges form a continuous loop (e.g., employee A gives a gift to B, B gives to C, and C gives back to A).
Return the result ordered by the chain length and total gift value of the chain in descending order.
The result format is in the following example.
Examples
Example 1:
|
|
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.