> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Freedom Trail Python Solution with Tests

> Tested Python solution for LeetCode 514 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 514, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Dynamic Programming](/catalog/topics/dynamic-programming), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search). [View on LeetCode](https://leetcode.com/problems/freedom-trail/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 514   # by problem number
lcpy gen -s freedom_trail   # by problem name
```

## Problem

In 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 to open the door.

Given a string `ring` that represents the code engraved on the outer ring and another string `key` that represents the keyword that needs to be spelled, return *the minimum number of steps to spell all the characters in the keyword*.

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

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

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

### Examples

![Example 1](https://assets.leetcode.com/uploads/2024/09/17/ring.jpg)

```
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.
```

```
Input: ring = "godding", key = "godding"
Output: 13
```

### Constraints

* `1 <= ring.length, key.length <= 100`
* `ring` and `key` consist of only lower case English letters.
* It is guaranteed that `key` could always be spelled by rotating `ring`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/freedom_trail/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/freedom_trail/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import defaultdict


class Solution:
    # Time: O(k * n^2) where n = len(ring), k = len(key)
    # Space: O(n)
    def find_rotate_steps(self, ring: str, key: str) -> int:
        n = len(ring)
        positions: dict[str, list[int]] = defaultdict(list)
        for i, char in enumerate(ring):
            positions[char].append(i)

        dp = [0] * n
        for k in range(len(key) - 1, -1, -1):
            next_dp = [float("inf")] * n
            for i in range(n):
                for j in positions[key[k]]:
                    clockwise = abs(i - j)
                    steps = min(clockwise, n - clockwise)
                    next_dp[i] = min(next_dp[i], steps + 1 + dp[j])
            dp = next_dp
        return int(dp[0])
```

## Complexity

| Time | Space |
| - | - |
| O(k \* n^2) where n = len(ring), k = len(key) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.