746. Minimum Runes to Add to Cast Spell

Alice, a newly graduated wizard, is ready to cast a grand spell. The spell consists of several magical nodes (focus points) where magic is concentrated. Some nodes already contain magic crystals that serve as power sources. These nodes can be connected using directed runes that channel magic from one node to another.

You are given :

  • An integer n representing the total number of magical nodes.
  • An array crystals where each element indicates a node that contains a magic crystal.
  • Two integer arrays, flowFrom and flowTo, where the rune at index i allows magic to flow from node flowFrom[i] to node flowTo[i].

Your task is to determine the minimum number of additional directed runes Alice must add so that every node either :

  • Contains a magic crystal, or
  • Receives magic flow from another node.

Example 1:

Input : n = 5, crystals = [2], flowFrom = [0, 1, 2], flowTo = [1, 2, 0]

Output : 2

Explanation :

Add two new runes:

  • From node 2 to node 3.
  • From node 2 to node 4.
  • Now, every node either contains a crystal (node 2) or receives magic from node 2.

Example 2:

Input : n = 6, crystals = [1, 4], flowFrom = [0, 1, 3], flowTo = [2, 3, 0]

Output : 1

Explanation :

By adding a rune from node 3 to node 5, each node is either powered by a crystal or receives magic flow:

  • Nodes 1 and 4 already have crystals.
  • The added connection from node 3 ensures that node 5 receives magic.

Now Your Turn!

Pick the correct output for the given input

Input : n = 4, crystals = [0, 3], flowFrom = [1], flowTo = [2]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 ≤ n ≤ 105
  • 1 ≤ crystals.length ≤ n
  • 0 ≤ crystals[i] ≤ n - 1
  • 1 ≤ flowFrom.length = flowTo.length ≤ min(2×105, n×(n - 1)/2)
  • 0 ≤ flowFrom[i], flowTo[i] ≤ n - 1
  • flowFrom[i] ≠ flowTo[i]
  • All pre-existing directed runes are distinct.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minRunesToAdd(int n, vector<int>& crystals, vector<int>& flowFrom, vector<int>& flowTo) {
// Your code goes here
}
};
Test Case

Input:

Crystals
Flow From
Flow To
N