Minimum Runes to Add to Cast Spell - Problem
Alice has just graduated from wizard school and wants to cast a magical spell to celebrate! ๐งโโ๏ธโจ
The spell consists of n focus points (numbered from 0 to n-1), where magic energy flows through a network of directed runes. Some focus points contain magic crystals that serve as energy sources, while others must receive magic flow from connected points.
You are given:
n: number of focus pointscrystals[]: array of focus point indices that contain magic crystalsflowFrom[]andflowTo[]: existing directed runes where magic flows fromflowFrom[i]toflowTo[i]
For the spell to work, every focus point must either:
- Contain a magic crystal, OR
- Receive magic flow from another focus point via a rune
Goal: Find the minimum number of additional directed runes Alice needs to add so that every focus point satisfies one of the above conditions.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 4, crystals = [0], flowFrom = [0], flowTo = [1]
โบ
Output:
2
๐ก Note:
Focus point 0 has crystal, point 1 receives flow from 0. Points 2 and 3 need magic flow, so we need 2 additional runes to connect them to the crystal network.
example_2.py โ Chain Connection
$
Input:
n = 3, crystals = [0], flowFrom = [0, 1], flowTo = [1, 2]
โบ
Output:
0
๐ก Note:
All points are connected in a chain: 0โ1โ2. Point 0 has crystal, point 1 receives from 0, point 2 receives from 1. No additional runes needed.
example_3.py โ Multiple Components
$
Input:
n = 6, crystals = [0, 3], flowFrom = [1, 4], flowTo = [2, 5]
โบ
Output:
2
๐ก Note:
Points 0,3 have crystals. Point 2 receives from 1, point 5 receives from 4. Points 1 and 4 need connections to crystal-bearing points. Need 2 runes: connect 1 to 0, and 4 to 3.
Visualization
Tap to expand
Understanding the Visualization
1
Map the Network
Identify all crystal sources and existing rune connections
2
Trace Power Flow
Use DFS to find all focus points reachable from crystals
3
Find Isolated Areas
Identify focus points that cannot reach any crystal source
4
Connect Efficiently
Add minimum runes to connect isolated components to the main network
Key Takeaway
๐ฏ Key Insight: Use graph traversal to identify reachable vs isolated components, then connect them with minimal new runes
Time & Space Complexity
Time Complexity
O(n + m)
n is focus points, m is existing runes - single DFS traversal
โ Linear Growth
Space Complexity
O(n + m)
Store adjacency list and visited arrays for DFS
โก Linearithmic Space
Constraints
- 1 โค n โค 105
- 0 โค crystals.length โค n
- 0 โค crystals[i] < n
- 0 โค flowFrom.length = flowTo.length โค min(n*(n-1), 105)
- 0 โค flowFrom[i], flowTo[i] < n
- flowFrom[i] โ flowTo[i]
- All crystal indices are unique
- No duplicate runes in input
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code