Engineering platform~35 min2s · 256 MBtarget O(W × L × (L + 25)) time, O(W × L) spaceclassic twin: lc-127bfs
A deployment tool renames a configuration key without downtime. It changes one letter at a time, and every key it passes through must be on a list of approved names.
Several plans can be equally short. Two plans are different when they pass through different keys at any step. The team wants to know how many shortest plans exist, so that the tool can pick one of them at random and spread the load.
Write count_shortest_rewrites(begin, goal, names).
begin and goal are keys of the same length. names lists the approved keys, all of that length. A key may be listed more than once.names. The first key, begin, does not need to be approved.begin to goal. Count the plans with the fewest steps and return the count modulo 1,000,000,007.1 when begin equals goal (the plan with no steps), and 0 when no plan exists.Input: begin = "red", goal = "tax", names = ["ted", "rex", "tex", "rad", "tad", "tax"]
Output: 4Every shortest plan has 3 steps. The solution counts plans layer by layer. A key in layer k is reached by k steps. Its count is the sum of the counts of the keys in layer k - 1 that are one change away.
| Layer | Names reached | Ways to reach each |
|---|---|---|
| 0 | red |
1 |
| 1 | rad, rex, ted |
1, 1, 1 |
| 2 | tad, tex |
2, 2 |
| 3 | tax |
4 |
The goal tax is reached 4 ways: through tex (2 ways) and through tad (2 ways).
Input: begin = "ab", goal = "ab", names = []
Output: 1The start is the goal, so the plan with no steps is the only one.
Input: begin = "aa", goal = "cc", names = ["ab", "cc"]
Output: 0From aa the only approved key one change away is ab, and cc is two changes from ab. No plan exists.
1 ≤ len(begin) = len(goal) ≤ 130 ≤ len(names) ≤ 10,000, and every name has the same length as beginComparing every pair of names would take about 49,995,000 comparisons. Grouping the names by wildcard pattern avoids that, because a key has only L patterns and each pattern holds at most 26 names. The plan count can also be huge. With 13 letters, one start and one goal can have 6,227,020,800 shortest plans, so the count must be reduced as it grows.