KatInterview

514. Freedom Trail

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum total steps to spell a given key string using a circular ring of characters. For each character in the key, we must rotate the ring to align the character at a specific position (12:00) and then press a button. Both rotating and pressing count as steps.

Solution

Freedom Trail in Python

import collections

class Solution:
    def findRotateSteps(self, ring: str, key: str) -> int:
        n = len(ring)
        m = len(key)
        
        char_positions = collections.defaultdict(list)
        for i, char in enumerate(ring):
            char_positions[char].append(i)
            
        # Use a dictionary for sparse DP states to be more efficient.
        # State: {ring_position: min_cost}
        # dp represents costs for the previous character in key.
        dp = {0: 0} # Initial state: ring[0] is at 12:00, cost 0.
        
        for char_to_spell in key:
            next_dp = collections.defaultdict(lambda: float('inf'))
            # For each occurrence of the character to spell
            for curr_pos in char_positions[char_to_spell]:
                min_cost = float('inf')
                # From each possible previous state
                for prev_pos, prev_cost in dp.items():
                    dist = abs(curr_pos - prev_pos)
                    rotation_steps = min(dist, n - dist)
                    cost = prev_cost + rotation_steps + 1 # +1 for press
                    min_cost = min(min_cost, cost)
                
                next_dp[curr_pos] = min(next_dp[curr_pos], min_cost)
            dp = next_dp

        return min(dp.values())

Freedom Trail in Java

class Solution {
    public int findRotateSteps(String ring, String key) {
        int n = ring.length();
        int m = key.length();
        Map<Character, List<Integer>> charPositions = new HashMap<>();
        for (int i = 0; i < n; i++) {
            char c = ring.charAt(i);
            charPositions.computeIfAbsent(c, k -> new ArrayList<>()).add(i);
        }

        // dp[j] stores the minimum steps to spell the prefix of the key processed so far,
        // with ring[j] at the 12:00 position.
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0; // Initial state: ring[0] is at 12:00, cost is 0.

        for (int i = 0; i < m; i++) { // For each character in key
            int[] next_dp = new int[n];
            Arrays.fill(next_dp, Integer.MAX_VALUE);
            char charToSpell = key.charAt(i);

            // For each occurrence of the character to spell on the ring
            for (int currPos : charPositions.get(charToSpell)) {
                int minPrevCost = Integer.MAX_VALUE;
                // From each possible previous state (where the previous character could have been spelled)
                for (int prevPos = 0; prevPos < n; prevPos++) {
                    if (dp[prevPos] == Integer.MAX_VALUE) {
                        continue;
                    }
                    int dist = Math.abs(currPos - prevPos);
                    int rotationSteps = Math.min(dist, n - dist);
                    minPrevCost = Math.min(minPrevCost, dp[prevPos] + rotationSteps);
                }
                if (minPrevCost != Integer.MAX_VALUE) {
                    next_dp[currPos] = minPrevCost + 1; // +1 for pressing the button
                }
            }
            dp = next_dp;
        }

        int result = Integer.MAX_VALUE;
        for (int val : dp) {
            result = Math.min(result, val);
        }
        return result;
    }
}

Freedom Trail in C++

class Solution {
public:
    int findRotateSteps(string ring, string key) {
        int n = ring.length();
        int m = key.length();
        unordered_map<char, vector<int>> char_positions;
        for (int i = 0; i < n; ++i) {
            char_positions[ring[i]].push_back(i);
        }

        // dp[j] stores the minimum steps to spell the prefix of the key processed so far,
        // with ring[j] at the 12:00 position.
        vector<int> dp(n, 1e9);
        dp[0] = 0; // Initial state: ring[0] is at 12:00, cost is 0.

        for (int i = 0; i < m; ++i) { // For each character in key
            vector<int> next_dp(n, 1e9);
            char char_to_spell = key[i];

            // For each occurrence of the character to spell on the ring
            for (int curr_pos : char_positions[char_to_spell]) {
                int min_prev_cost = 1e9;
                // From each possible previous state (where the previous character could have been spelled)
                for (int prev_pos = 0; prev_pos < n; ++prev_pos) {
                    if (dp[prev_pos] == 1e9) continue;

                    int dist = abs(curr_pos - prev_pos);
                    int rotation_steps = min(dist, n - dist);
                    min_prev_cost = min(min_prev_cost, dp[prev_pos] + rotation_steps);
                }
                if (min_prev_cost != 1e9) {
                    next_dp[curr_pos] = min_prev_cost + 1; // +1 for pressing the button
                }
            }
            dp = next_dp;
        }

        int result = 1e9;
        for (int val : dp) {
            result = min(result, val);
        }

        return result;
    }
};

Freedom Trail in TypeScript

function findRotateSteps(ring: string, key: string): number {
    const n = ring.length;
    const m = key.length;
    const charPositions = new Map<string, number[]>();
    for (let i = 0; i < n; i++) {
        const char = ring[i];
        if (!charPositions.has(char)) {
            charPositions.set(char, []);
        }
        charPositions.get(char)!.push(i);
    }

    // dp[j] stores min steps to spell prefix of key processed so far,
    // with ring[j] at 12:00.
    let dp = new Array(n).fill(Infinity);
    dp[0] = 0; // Initial state: ring[0] at 12:00, cost 0.

    for (let i = 0; i < m; i++) { // For each character in key
        const next_dp = new Array(n).fill(Infinity);
        const charToSpell = key[i];

        // For each occurrence of the character to spell on the ring
        for (const currPos of charPositions.get(charToSpell)!) {
            let minPrevCost = Infinity;
            // From each possible previous state
            for (let prevPos = 0; prevPos < n; prevPos++) {
                if (dp[prevPos] === Infinity) {
                    continue;
                }
                const dist = Math.abs(currPos - prevPos);
                const rotationSteps = Math.min(dist, n - dist);
                minPrevCost = Math.min(minPrevCost, dp[prevPos] + rotationSteps);
            }
            if (minPrevCost !== Infinity) {
                next_dp[currPos] = minPrevCost + 1; // +1 for pressing the button
            }
        }
        dp = next_dp;
    }

    let result = Infinity;
    for (const val of dp) {
        result = Math.min(result, val);
    }
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.