Find Circular Gift Exchange Chains - Problem
Imagine it's the holiday season at your company, and employees are participating in a Secret Santa gift exchange! ๐
You're given a table SecretSanta that records all the gift exchanges between employees. Your task is to find all the circular chains of gift exchanges and calculate their total value.
A circular chain is a special pattern 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., A โ B โ C โ A)
For each circular chain found, you need to return:
- chain_id: A unique identifier for the chain
- chain_length: Number of employees in the chain
- total_gift_value: Sum of all gift values in the chain
Results should be ordered by chain length and total gift value in descending order.
Input & Output
example_1.py โ Basic Circular Chains
$
Input:
SecretSanta = [[1,2,20], [2,3,30], [3,1,40], [4,5,25], [5,4,35]]
โบ
Output:
[[1,3,90], [2,2,60]]
๐ก Note:
Two circular chains found: Chain 1 (1โ2โ3โ1) with length 3 and total value $90, Chain 2 (4โ5โ4) with length 2 and total value $60. Ordered by chain length desc, then total value desc.
example_2.py โ Single Large Chain
$
Input:
SecretSanta = [[1,2,10], [2,3,15], [3,4,20], [4,1,25]]
โบ
Output:
[[1,4,70]]
๐ก Note:
One circular chain of length 4: employees 1โ2โ3โ4โ1. Total gift value = 10+15+20+25 = $70.
example_3.py โ No Circular Chains
$
Input:
SecretSanta = [[1,2,100], [3,4,200], [5,6,300]]
โบ
Output:
[]
๐ก Note:
No circular chains exist - each exchange is a one-way gift with no return path, so no employee both gives and receives in a continuous loop.
Constraints
- 1 โค number of exchanges โค 1000
- 1 โค giver_id, receiver_id โค 1000
- 1 โค gift_value โค 104
- Each employee can give at most one gift
- Circular chains must have at least 1 participant
Visualization
Tap to expand
Understanding the Visualization
1
Model as Graph
Each employee is a node, each gift exchange is a directed edge
2
Detect Cycles
Use DFS to find closed loops where gift flow returns to starting employee
3
Calculate Metrics
For each cycle, count participants and sum all gift values
4
Sort Results
Order chains by length (descending), then by total value (descending)
Key Takeaway
๐ฏ Key Insight: Transform the gift exchange problem into cycle detection in a directed graph. Each employee has exactly one outgoing edge, making DFS cycle detection optimal with O(V + E) complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code