Magicsheet logo

Freedom Trail

Hard
12.5%
Updated 8/1/2025

Freedom Trail

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

This is solved using 2D Dynamic Programming (or Memoization).

  1. State: 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].
  2. Transitions: For the current character key[key_index], find all its occurrences on the ring.
  3. For each occurrence at index i, calculate the rotation distance from ring_index to i (minimum of clockwise and counter-clockwise).
  4. Add 1 for the button press, and recursively call dp(i, key_index + 1).
  5. Take the minimum over all occurrences.

Example explanation

ring = "godding", key = "gd"

  • Start at index 0 ('g'). Need 'g'. It's at index 0 and 6.
  • Option 1 (Use 'g' at 0): Distance 0. Press button (+1). Now need 'd'. Pointer at 0.
    • 'd' is at index 2 and 3.
    • Go to 2: dist 2. Total so far: 1 + 2 + 1 = 4.
    • Go to 3: dist 3. Total so far: 1 + 3 + 1 = 5.
  • Option 2 (Use 'g' at 6): Distance 1 (counter-clockwise). Press (+1). Now need 'd'. Pointer at 6.
    • Go to 2: dist 4. Total: 2 + 4 + 1 = 7.
    • Go to 3: dist 3. Total: 2 + 3 + 1 = 6. Minimum is 4 steps.

Common mistakes candidates make

  • Greedy Approach: Always picking the closest instance of the required character. This fails when a slightly longer move sets you up perfectly for the rest of the string.
  • Distance Calculation: Incorrectly handling the circular wrap-around distance. The shortest distance between a and b on a ring of length n is min(abs(a - b), n - abs(a - b)).
  • Missing Button Press: Forgetting to add 1 step for "pressing the button" for each character in the key.

Interview preparation tip

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.

Similar Questions