Freedom Trail LeetCode Solution

Last updated on October 25th, 2024 at 10:38 pm

Here, We see Freedom Trail LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Depth-First Search, Divide-and-Conquer, Dynamic Programming

Companies

Google

Level of Question

Hard

Freedom Trail LeetCode Solution

Freedom Trail LeetCode Solution

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:

ring

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

1. Freedom Trail LeetCode Solution C++

class Solution {
public:
    int dist(int size, int p, int t){
        return min(abs(t - p), size - abs(t - p));
    }
    int findRotateSteps(string ring, string key){
        int m[26][100] = {{0}};
        int cnt[26] = {0};
        int dp[100][100] = {{0}};

        const int rn = ring.size();
        const int kn = key.size();
        for(int i = 0; i < rn; ++i)
            m[ring[i]-'a'][cnt[ring[i]-'a']++] = i;
        for(int i = 0; i < cnt[key[0]-'a']; ++i){
                dp[0][m[key[0]-'a'][i]] = dist(rn, 0, m[key[0]-'a'][i]) + 1;
        }
        for(int i = 1; i < kn; ++i){
            for(int j = 0; j < cnt[key[i]-'a']; ++j){
                int mini = INT_MAX;
                for(int k = 0; k < cnt[key[i-1]-'a']; ++k){
                    mini = min(mini, dp[i-1][m[key[i-1]-'a'][k]] + dist(rn, m[key[i]-'a'][j], m[key[i-1]-'a'][k]) + 1);
                }
                dp[i][m[key[i]-'a'][j]] = mini;
            }
        }
        int res = INT_MAX;
        for(int i = 0; i < cnt[key.back()-'a']; ++i){
            res = min(res, dp[kn-1][m[key[kn-1]-'a'][i]]);
        }
        return res;
    }
};

2. Freedom Trail LeetCode Solution Java

class Solution {
    public int findRotateSteps(String ring, String key) {
        char[] r=ring.toCharArray();
        List<Integer>[] p=new List[26];
        for(int i=0;i<r.length;i++) {
            int c=r[i]-'a';
            List<Integer> l=p[c];
            if(l==null) p[c]=l=new ArrayList<>();
            l.add(i);
        }
        return helper(0,0,p,key.toCharArray(),ring,new int[key.length()][r.length]);
    }
    int helper(int in, int pos, List<Integer>[] p, char[] k, String r, int[][] memo) {
        if(in==k.length) return 0;
        if(memo[in][pos]>0) return memo[in][pos]-1;
        int min=Integer.MAX_VALUE;
        for(int i: p[k[in]-'a']) {
            int m;
            if(i>=pos) m=Math.min(i-pos,pos+r.length()-i);
            else m=Math.min(pos-i,i+r.length()-pos);
            min=Math.min(min,m+helper(in+1,i,p,k,r,memo));
        }
        return (memo[in][pos]=min+2)-1;
    }
}

3. Freedom Trail LeetCode Solution JavaScript

var findRotateSteps = function (ring, key) {
    let left = i => i === 0 ? ring.length - 1 : i - 1;
    let right = i => i === ring.length - 1 ? 0 : i + 1;
    let dp = ring.split("").map(() => 0);
    for (let i = key.length - 1; i >= 0; i--) {
        let dp1 = ring.split("").map((x, j) => (x === key[i]) ? dp[j] : Infinity);
        for (let j = 0; j < ring.length * 2; j++) {
            let x = j % ring.length;
            dp1[x] = Math.min(dp1[x], dp1[left(x)] + 1);
            let y = ((ring.length * 2) - 1 - j) % ring.length;
            dp1[y] = Math.min(dp1[y], dp1[right(y)] + 1);
        }
        dp = dp1;
    }
    return dp[0] + key.length;
};

4. Freedom Trail LeetCode Solution Python

class Solution(object):
    def findRotateSteps(self, ring, key):
        visited = {}
        heap = [[0, 0, ring]]
        heapq.heapify(heap)
        while len(heap) > 0:
            step, ltr_to_match, pattern = heapq.heappop(heap)
            if (pattern, ltr_to_match) in visited and visited[(pattern, ltr_to_match)] <= step:
                continue
            visited[(pattern, ltr_to_match)] = step
            while ltr_to_match < len(key) and pattern[0] == key[ltr_to_match]:
                ltr_to_match += 1
                step += 1 #press button
            if ltr_to_match == len(key):
                return step
            heapq.heappush(heap, [step + 1, ltr_to_match, pattern[-1] + pattern[:len(pattern)-1]])
            heapq.heappush(heap, [step + 1, ltr_to_match, pattern[1:] + pattern[:1]])
Scroll to Top