TopCoder problem "Wizarding" used in TCHS SRM 2 (Division I Level Three)

Problem Statement

    A spell is defined by its incantation, the word spoken when the spell is being cast. If you know the incantation of a spell, you can create counterspells in the following manner. First, you can optionally delete any number of characters from the original incantation. Note that empty incantations are not valid so you cannot delete all characters. Then, you can replace any number of the remaining characters according to a set of replacement rules. The replacement rules tell you which letters can be replaced, and the letters with which they can be replaced. For example, if the original incantation is "AA" and the allowed replacement is 'A' to 'Z', the following counterspells are possible: "AA", "A", "Z", "ZZ", "AZ", "ZA".

The best counterspell is the one with the greatest power. The power of a spell is the product of all its character values modulo 77077, where the value for a character is its position in the alphabet (character 'A' has value 1, character 'B' value 2, character 'C' value 3, and so on). The best possible counterspell for "AA" in the example above is "ZZ", which has a power of 676.

Please note that if the allowed replacements are 'A' to 'B' and 'B' to 'C', the counterspell for "AB" is "BC" not "CC". You cannot change a character that has already been changed, even if it would lead to a more powerful spell.

You will be given a String spell, the incantation of the spell you are going to counter, and a String rules, the allowed replacements for letters. The first character in rules is the allowed replacement for the letter 'A', the second for 'B' and so on. The character '-' is used to denote a letter that cannot be replaced. Your program must return a String, the most powerful counterspell available. If multiple return values are possible, return the shortest among them. If a tie still exists return the lexicographically earliest.


Parameters:String, String
Method signature:String counterspell(String spell, String rules)
(be sure your method is public)


-spell will contain between 1 and 13 characters, inclusive.
-spell will contain only uppercase letters ('A'-'Z').
-rules will contain exactly 26 characters.
-rules will contain only uppercase letters ('A'-'Z') and dashes ('-').


Returns: "ZZ"
The example from the problem statement.
Returns: "ZS"
The possible counterspells are "AB", "A", "B", "Z", "S", "ZB", "AS" and "ZS".

"ZS" is the most powerful.
Returns: "ZZZZ"
Returns: "ZXXE"
Returns: "CCDECCECC"

Problem url:

Problem stats url:




PabloGilberto , brett1479 , Olexiy

Problem categories:

Brute Force, Recursion