Freedom Trail — LeetCode 514 Python Solution
- Problem
- #514
- Pattern
- Breadth-First Search
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
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.
Python solution
class Solution:
def findRotateSteps(self, ring: str, key: str) -> int:
m, n = len(key), len(ring)
pos = defaultdict(list)
for i, c in enumerate(ring):
pos[c].append(i)
f = [[inf] * n for _ in range(m)]
for j in pos[key[0]]:
f[0][j] = min(j, n - j) + 1
for i in range(1, m):
for j in pos[key[i]]:
for k in pos[key[i - 1]]:
f[i][j] = min(
f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1
)
return min(f[-1][j] for j in pos[key[-1]])Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n^2) |
| Space | O(m \times n) auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 514. Freedom Trail is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 514. Freedom Trail?
- LeetCode 514. Freedom Trail is rated Hard on LeetCode.
- What is the time complexity of LeetCode 514. Freedom Trail?
- The Python solution on this page runs in O(m \times n^2).
- What is the space complexity of LeetCode 514. Freedom Trail?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 514. Freedom Trail cover?
- LeetCode 514. Freedom Trail is tagged Depth-First Search, Breadth-First Search, String and Dynamic Programming on LeetCode.