Minimum Runes to Add to Cast Spell - Problem

Alice has just graduated from wizard school and wishes to cast a magic spell to celebrate. The magic spell contains certain focus points where magic needs to be concentrated, and some of these focus points contain magic crystals which serve as the spell's energy source.

Focus points can be linked through directed runes, which channel magic flow from one focus point to another. You are given an integer n denoting the number of focus points and an array of integers crystals where crystals[i] indicates a focus point which holds a magic crystal.

You are also given two integer arrays flowFrom and flowTo, which represent the existing directed runes. The i-th rune allows magic to freely flow from focus point flowFrom[i] to focus point flowTo[i].

You need to find the number of directed runes Alice must add to her spell, such that each focus point either:

  • Contains a magic crystal, OR
  • Receives magic flow from another focus point

Return the minimum number of directed runes that she should add.

Input & Output

Example 1 — Basic Magic Spell
$ Input: n = 4, crystals = [0], flowFrom = [1], flowTo = [2]
Output: 2
💡 Note: Focus point 0 has a crystal (satisfied). Focus point 2 receives flow from point 1 (satisfied). Focus points 1 and 3 need additional runes to be satisfied, so answer is 2.
Example 2 — Multiple Crystals
$ Input: n = 3, crystals = [0, 2], flowFrom = [], flowTo = []
Output: 1
💡 Note: Focus points 0 and 2 have crystals (satisfied). Focus point 1 has no crystal and receives no flow, so needs 1 additional rune.
Example 3 — All Satisfied
$ Input: n = 2, crystals = [0], flowFrom = [0], flowTo = [1]
Output: 0
💡 Note: Focus point 0 has a crystal and focus point 1 receives flow from point 0. All points are satisfied, so no additional runes needed.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ crystals.length ≤ n
  • 0 ≤ crystals[i] < n
  • 0 ≤ flowFrom.length = flowTo.length ≤ 105
  • 0 ≤ flowFrom[i], flowTo[i] < n

Visualization

Tap to expand
Magic Spell Focus Points Network0123Crystal ✓Needs RuneGets Flow ✓Needs RuneAdd rune to 1Add rune to 3Minimum runes needed: 2
Understanding the Visualization
1
Focus Points
4 focus points numbered 0-3
2
Crystals & Flow
Point 0 has crystal, flow goes 1→2
3
Missing Connections
Points 1 and 3 need additional runes
Key Takeaway
🎯 Key Insight: Count nodes that neither have crystals nor receive flow
Asked in
Google 15 Amazon 12 Facebook 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen