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]:
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].
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.
Example 1:
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.
Example 2:
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.
Problem summary: 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]: You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"godding"
"gd"
Example 2
"godding"
"godding"
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #514: Freedom Trail
class Solution {
public int findRotateSteps(String ring, String key) {
int m = key.length(), n = ring.length();
List<Integer>[] pos = new List[26];
Arrays.setAll(pos, k -> new ArrayList<>());
for (int i = 0; i < n; ++i) {
int j = ring.charAt(i) - 'a';
pos[j].add(i);
}
int[][] f = new int[m][n];
for (var g : f) {
Arrays.fill(g, 1 << 30);
}
for (int j : pos[key.charAt(0) - 'a']) {
f[0][j] = Math.min(j, n - j) + 1;
}
for (int i = 1; i < m; ++i) {
for (int j : pos[key.charAt(i) - 'a']) {
for (int k : pos[key.charAt(i - 1) - 'a']) {
f[i][j] = Math.min(
f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1);
}
}
}
int ans = 1 << 30;
for (int j : pos[key.charAt(m - 1) - 'a']) {
ans = Math.min(ans, f[m - 1][j]);
}
return ans;
}
}
// Accepted solution for LeetCode #514: Freedom Trail
func findRotateSteps(ring string, key string) int {
m, n := len(key), len(ring)
pos := [26][]int{}
for j, c := range ring {
pos[c-'a'] = append(pos[c-'a'], j)
}
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = 1 << 30
}
}
for _, j := range pos[key[0]-'a'] {
f[0][j] = min(j, n-j) + 1
}
for i := 1; i < m; i++ {
for _, j := range pos[key[i]-'a'] {
for _, k := range pos[key[i-1]-'a'] {
f[i][j] = min(f[i][j], f[i-1][k]+min(abs(j-k), n-abs(j-k))+1)
}
}
}
ans := 1 << 30
for _, j := range pos[key[m-1]-'a'] {
ans = min(ans, f[m-1][j])
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #514: Freedom Trail
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]])
// Accepted solution for LeetCode #514: Freedom Trail
struct Solution;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
fn find_rotate_steps(ring: String, key: String) -> i32 {
let n = ring.len();
let m = key.len();
let ring: Vec<char> = ring.chars().collect();
let key: Vec<char> = key.chars().collect();
let mut queue: BinaryHeap<(Reverse<i32>, usize, usize)> = BinaryHeap::new();
let mut dist = vec![vec![std::i32::MAX; n]; m];
queue.push((Reverse(0), 0, 0));
while let Some((Reverse(step), i, size)) = queue.pop() {
if size == m {
return step;
}
for j in 0..n {
if ring[j] == key[size] {
let d = step + Self::rotate(i as i32, j as i32, n as i32) + 1;
if d < dist[size][j] {
dist[size][j] = d;
queue.push((Reverse(d), j, size + 1));
}
}
}
}
0
}
fn rotate(i: i32, j: i32, n: i32) -> i32 {
let left = i - j;
let right = j - i;
let left = if left < 0 { left + n } else { left };
let right = if right < 0 { right + n } else { right };
left.min(right)
}
}
#[test]
fn test() {
let ring = "godding".to_string();
let key = "gd".to_string();
let res = 4;
assert_eq!(Solution::find_rotate_steps(ring, key), res);
}
// Accepted solution for LeetCode #514: Freedom Trail
function findRotateSteps(ring: string, key: string): number {
const m: number = key.length;
const n: number = ring.length;
const pos: number[][] = Array.from({ length: 26 }, () => []);
for (let i = 0; i < n; ++i) {
const j: number = ring.charCodeAt(i) - 'a'.charCodeAt(0);
pos[j].push(i);
}
const f: number[][] = Array.from({ length: m }, () => Array(n).fill(1 << 30));
for (const j of pos[key.charCodeAt(0) - 'a'.charCodeAt(0)]) {
f[0][j] = Math.min(j, n - j) + 1;
}
for (let i = 1; i < m; ++i) {
for (const j of pos[key.charCodeAt(i) - 'a'.charCodeAt(0)]) {
for (const k of pos[key.charCodeAt(i - 1) - 'a'.charCodeAt(0)]) {
f[i][j] = Math.min(
f[i][j],
f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1,
);
}
}
}
let ans: number = 1 << 30;
for (const j of pos[key.charCodeAt(m - 1) - 'a'.charCodeAt(0)]) {
ans = Math.min(ans, f[m - 1][j]);
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(m × n^2)
Space
O(m × n)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.