Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

514. Freedom Trail

Hard58.9% Acceptance
StringDynamic ProgrammingDepth-First Search
Asked by:
DE Shaw
ProblemSolutions (6)VideosCompanies (2)Notes

Problem Statement

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.

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.
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
D
G
Google

Approach

The key idea in #514 Freedom Trail is to model the ring rotations efficiently while spelling the target key. Each character in the key can be matched at multiple positions in the circular ring, so the challenge is minimizing the rotation cost between consecutive characters.

A common approach is to use dynamic programming with memoization. First, map each character in the ring to all indices where it appears. Then, for each position in the key and current ring index, compute the minimum steps needed to reach all valid next positions. The rotation cost is the minimum distance in a circular array: min(|i-j|, n-|i-j|), plus one step for pressing the button.

Using DFS with memoization or iterative DP avoids recomputation and efficiently explores valid transitions. This significantly reduces the state space compared to brute force.

The typical complexity is around O(m * n * k), where m is the key length, n is the ring length, and k is the average number of occurrences of each character.

Complexity

ApproachTime ComplexitySpace Complexity
Dynamic Programming with DFS + MemoizationO(m * n * k)O(m * n)

Video Solution Available

PunchNshoot

View all video solutions

Solutions (6)

Dynamic Programming with Memoization

In this approach, we'll use a recursive solution with memoization to efficiently calculate the minimum number of steps. The function will take the current position in the ring and the current index in the key string as parameters, and will calculate the optimal steps required for each character. We'll cache the results of subproblems to avoid recalculating them.

Time Complexity: O(m*n), where m is the length of the `key` and n is the length of the `ring`.
Space Complexity: O(m*n) for the memoization table and index dictionary.

PythonJavaC++
1def min_steps(ring, key):
2    from collections import defaultdict
3
4    def dp(pos, idx):
5        if idx == len(key):
6            return 0
7        if (pos, idx) in memo:
8            return memo[(pos, idx)]
9        res = float('inf')
10        for k in ring_indices[key[idx]]:
11            diff = abs(pos - k)
12            step = min(diff, len(ring) - diff) + 1
13            res = min(res, step + dp(k, idx + 1))
14        memo[(pos, idx)] = res
15        return res
16
17    ring_indices = defaultdict(list)
18    for i, char in enumerate(ring):
19        ring_indices[char].append(i)
20
21    memo = {}
22    return dp(0, 0)
23
24ring = 'godding'
25key = 'gd'
26print(min_steps(ring, key))  # Output: 4

Explanation

This solution defines a recursive function `dp` that returns the minimum steps from a given position `pos` in the ring to spell the remainder of the `key` starting from index `idx`. We use a hashmap `ring_indices` to find all positions in the `ring` that match the current character of `key`. For each potential position, we calculate the number of steps required to reach it from the current position, both clockwise and counter-clockwise, and add 1 for the press action. We store the solution in a memoization table to prevent recalculation.

Breadth-First Search Approach

In this approach, we'll leverage BFS to explore each possible state of the ring and propagate the minimum distance for each configuration. We can view each state as a node in a graph and use BFS to find the target node with minimum steps.

Time Complexity: O(n*m), where n is the length of the key and m is the length of the ring.
Space Complexity: O(n*m) for storing visited states in the queue.

PythonJavaJavaScript
1from collections import deque, defaultdict
2
3


Video Solutions

Watch expert explanations and walkthroughs

Freedom Trail Ring Combination Code - Fallout 4

PunchNshoot
2:321,022,796 views

Asked By Companies

2 companies
D
DE Shaw
G
Google

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Longest Palindromic SubstringMedium
Regular Expression MatchingHard
Generate ParenthesesMedium
Longest Valid ParenthesesHard
More similar problems

Related Topics

StringDynamic ProgrammingDepth-First SearchBreadth-First Search

Problem Stats

Acceptance Rate58.9%
DifficultyHard
Companies2

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Freedom Trail asked in FAANG interviews?

Yes, Freedom Trail is considered a strong interview-level problem because it combines strings, circular distance calculation, and dynamic programming. Variants of this problem can appear in FAANG and other top tech company interviews.

What data structure is best for Freedom Trail?

A hash map or dictionary that maps each character to all its indices in the ring is very useful. This allows quick access to possible positions for each key character and helps reduce unnecessary scanning.

What is the optimal approach for Freedom Trail?

The optimal approach uses dynamic programming with memoization. By mapping each character in the ring to its positions and calculating the minimum rotation distance between states, we can efficiently compute the minimum steps needed to spell the key.

Why is dynamic programming used in Freedom Trail?

Dynamic programming is used because the problem contains overlapping subproblems. The minimum cost to spell the rest of the key from a given ring position can be reused, which avoids recomputation and greatly improves efficiency.

def
min_steps_bfs
(
ring
,
key
)
:
4
ring_length
=
len
(
ring
)
5
indices_by_char
=
defaultdict
(
list
)
6
for
i
,
c
in
enumerate
(
ring
)
:
7
indices_by_char
[
c
]
.
append
(
i
)
8
9
queue
=
deque
(
[
(
0
,
0
)
]
)
# (ring_position, key_index)
10
visited
=
set
(
queue
)
11
steps
=
0
12
13
while
queue
:
14
for
_
in
range
(
len
(
queue
)
)
:
15
pos
,
idx
=
queue
.
popleft
(
)
16
if
idx
==
len
(
key
)
:
17
return
steps
18
for
k
in
indices_by_char
[
key
[
idx
]
]
:
19
if
(
k
,
idx
+
1
)
not
in
visited
:
20
visited
.
add
(
(
k
,
idx
+
1
)
)
21
queue
.
append
(
(
k
,
idx
+
1
)
)
22
steps
+=
1
23
24
ring
=
'godding'
25
key
=
'gd'
26
print
(
min_steps_bfs
(
ring
,
key
)
)
# Output: 4

Explanation

This solution uses a breadth-first search (BFS) approach to explore each state (current position and current character index in the key string). Each state is added to a queue along with the action step count. For each character in the key, we consider all possible indices in the ring where the character appears and add them to the queue, marking them as visited.