# 514. Freedom Trail

n the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.

Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.

Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.

At the stage of rotating the ring to spell the key character key[i]:

You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i]. If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.

Example:

Input: ring = "godding", key = "gd"
Output: 4
Explanation:
For the first key character 'g', since it is already in place, we just need 1 step to spell this character. 
For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
Also, we need 1 more step for spelling.
So the final output is 4.

# Solution

Approach 1: (memoized) backtracking.

Approach 2: DP.

# Code (Python)

Approach 1:

    def findRotateSteps0(self, ring: str, key: str) -> int:
        # backtracking (TLE)
        return len(key) + self._backtrack(ring, key, 0, 0)
    
    def _backtrack(self, ring, key, index, position):
        if index == len(key):
            return 0
        min_total_steps = float('inf')
        for letter_index in range(len(ring)):
            if ring[letter_index] == key[index]:
                # rotate to that position
                steps_needed = min(
                    (letter_index - position) % len(ring),
                    len(ring) - ((letter_index - position) % len(ring)) # x steps clockwise == (len(ring) - x) steps counterclockwise
                )
                min_total_steps = min(min_total_steps, steps_needed + self._backtrack(ring, key, index + 1, letter_index))
        return min_total_steps

Approach 2:

    def findRotateSteps(self, ring: str, key: str) -> int:
        # preprocess {letter: list of positions in ring} map
        letter_positions = {}
        key_letters = set(key)
        for i in range(len(ring)):
            if ring[i] in key_letters:
                if ring[i] not in letter_positions:
                    letter_positions[ring[i]] = []
                letter_positions[ring[i]].append(i)

        # record the min steps after the current key letter {position: min_steps} -- work backwards
        min_steps = {pos: 0 for pos in letter_positions[key[-1]]} # the last letter costs 0 steps
        for i in range(len(key) - 2, -1, -1):
            # for each position of the previous letter, record the min steps to get to any position of the next letter
            new_min_steps = {pos: float('inf') for pos in letter_positions[key[i]]}
            for position in letter_positions[key[i]]:
                for next_position, num_steps in min_steps.items():
                    new_min_steps[position] = min(
                        new_min_steps[position],
                        num_steps + (position - next_position) % len(ring),
                        num_steps + len(ring) - ((position - next_position) % len(ring))
                    )
            min_steps = new_min_steps
        
        # add costs for the first letter
        for pos in min_steps:
            min_steps[pos] += min(pos, len(ring) - pos)
        
        return len(key) + min(min_steps.values())

# Code (C++)

Approach 1:

Approach 2: