The Freedom Trail coding problem is inspired by a video game puzzle. You have a ring with characters written on it. The ring is aligned with a 12:00 position. You are given a key string that you need to spell out. To spell a character, you must rotate the ring (clockwise or counter-clockwise) so that the desired character is at 12:00, and then press a button. You want to find the minimum number of steps (rotations + button presses) to spell the entire key.
Google and Amazon ask the Freedom Trail interview question because it’s a "Hard" problem that beautifully combines string manipulation with the Dynamic Programming interview pattern. Since a character might appear multiple times on the ring, choosing the closest one right now might force you into a bad position for the next character. It tests your ability to avoid greedy traps and use DP to explore all optimal paths.
This is solved using 2D Dynamic Programming (or Memoization).
dp(ring_index, key_index) represents the minimum steps to spell key[key_index...] given that the 12:00 pointer is currently at ring[ring_index].key[key_index], find all its occurrences on the ring.i, calculate the rotation distance from ring_index to i (minimum of clockwise and counter-clockwise).dp(i, key_index + 1).ring = "godding", key = "gd"
a and b on a ring of length n is min(abs(a - b), n - abs(a - b)).Precompute the positions of each character in the ring using a Hash Map (char -> list of indices). This saves you from having to scan the ring string repeatedly during the DP transitions.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Edge Reversals So Every Node Is Reachable | Hard | Solve | |
| Serialize and Deserialize N-ary Tree | Hard | Solve | |
| Lexicographically Smallest String After Applying Operations | Medium | Solve | |
| Web Crawler | Medium | Solve | |
| String Compression II | Hard | Solve |