What is the freedom trail problem in Python?
We’re provided a string ring representing the code in our ring and another string key signifying the keyword that needs to be spelled. Our task is to find the minimum number of operations to spell out the target string.
To begin, the first character of the ring is positioned at the 12:00 position. We need to spell each separate character in key. For this, we’ll have to rotate the ring clockwise or counterclockwise, aligning each key character at the 12:00 position before counting the character.
Note: After aligning, confirming that character will also count as an additional step. In the diagram above, confirming A counts as one step. Moving B to 12:00 counts as another step, and confirming it also counts as a third step. Hence, the minimum steps are three.
Code
In our solution, we’ll be using a helper function to help calculate the minimum steps required to spell key. It uses memoization to store previous results and avoid redundant calculations. It iterates through ring and calculates the optimal rotations to return the minimum steps needed to complete the task.
The code for this solution is provided below:
def freedomtrail(ring, key):return fthelper(0, 0) + len(key)def fthelper(i, j):memo = {}if j == len(key):return 0if (i, j) in memo:return memo[(i, j)]char = key[j]minsteps = float('inf')for k in range(len(ring)):if ring[k] == char:rotate = abs(k - i)minsteps = min(minsteps, rotate + fthelper(k, j + 1))memo[(i, j)] = minstepsreturn minstepsring = "right"key = "rh"result = freedomtrail(ring, key)print("The minimum operations are: " + str(result))
The explanation of this code is given below:
Line 1: We define our
freedomtrailfunction, which takesringandkeyas parameters. It calculates the minimum steps needed to spell outkeystarting from index 0 ofring.Line 2: We call the
fthelperfunction with parameters(0, 0). We then add the length ofkeyto the result.Line 4: We define the
fthelperfunction, which takes the indexesiandjas parameters.Line 5: We define an empty dictionary
memoto store our steps.Lines 6–7: This is the base case check for when
jreaches the length ofkey. This will indicate that we’ve spelled the word.Lines 9–10: We check whether we’ve traversed this path in the dictionary.
Line 12: We extract the character we need to search in the ring.
Line 13: We set
minstepsto positive infinity to store the actual minimum number of steps later on.Line 15: We loop through the entire ring.
Lines 16–18: Each time the character is found at index
k, we calculate the steps required to rotate theringfrom indexitok. We recursively callfthelperwith the new positionkalong withj + 1to match the next character we need inkey. We then update the minimum steps required among all possible rotations in the ring.Lines 20–21: We update and store the minimum steps required for the indexes in
memoto avoid recalculations. We then returnminsteps.Lines 23–26: This is the code to run our functions.
To try other examples, you can change the inputs in the code above.
Free Resources