Problem 514

Abstract / Summary

Find the minimum steps to spell a target string on a circular keyboard starting from a given letter.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0514.py

class Solution:
    def findRotateSteps(self, ring: str, key: str) -> int:
        # simply brute force with a little caching

        # positions of each letter
        letters = defaultdict(list)
        for i, c in enumerate(ring):
            letters[c].append(i)

        @cache
        def deeper(index = 0, rotation = 0): # index => position in key
            if index == len(key):
                return 0

            best = 9999
            for i in letters[key[index]]:
                # consider wraparound, too
                closest = min(abs(rotation - i), len(ring) - abs(rotation - i))
                steps = closest + deeper(index + 1, i)
                best  = min(best, steps)

            return best + 1 # press button, too

        return deeper()
24 lines | 799 bytes | submitted March 29, 2024 | GitHub   31% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (200k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Dynamic Programming
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the “Freedom Trail” problem: given a circular ring of characters and a target key, it computes the minimum number of steps required to spell the key. A step consists of rotating the ring one position clockwise or counter-clockwise, plus one step for pressing the button to confirm a character. The algorithm combines a preprocessing phase that records every occurrence of each letter in the ring with a depth-first search that is memoized to avoid redundant work.

Key Steps

Preprocessing the Ring

The first phase builds a mapping from each character to the list of indices where that character appears in the ring. This enables constant-time lookup of all possible rotation targets for a given key character.

letters = defaultdict(list)
for i, c in enumerate(ring):
    letters[c].append(i)

The use of defaultdict(list) automatically creates an empty list for a character the first time it is encountered, so the code never raises a KeyError. The resulting letters dictionary contains entries such as 'a': [0, 5, 9] when the character 'a' appears at those positions.

Recursive Search with Memoization

The core of the solution is a recursive function deeper that explores every way to align the ring for the remaining suffix of the key. The function is decorated with @cache, which stores the result for each pair (index, rotation). Because the same state can be reached through different paths, caching eliminates exponential blow-up.

@cache
def deeper(index = 0, rotation = 0):
    if index == len(key):
        return 0

    best = 9999
    for i in letters[key[index]]:
        closest = min(abs(rotation - i), len(ring) - abs(rotation - i))
        steps = closest + deeper(index + 1, i)
        best  = min(best, steps)

    return best + 1   # press button
  • The base case (index == len(key)) returns 0 because no further rotations or button presses are needed once the entire key has been processed.
  • The loop iterates over every index i where the current key character appears in the ring.
  • closest computes the minimal rotation distance, taking the circular nature of the ring into account.
  • steps adds the rotation cost to the result of the recursive call for the next character, assuming the ring ends up at position i.
  • best tracks the smallest total cost among all possible positions for the current character.
  • After the loop, 1 is added to account for the button press that confirms the character.

Initiating the Search

The public method simply invokes the memoized recursive function with the initial state: the first character of the key (index = 0) and the ring aligned at position 0 (rotation = 0).

return deeper()

Because deeper is cached, the first call populates the memo table, and subsequent recursive calls reuse previously computed results.

Edge Cases Handled

When the key is an empty string, the base case of the recursion is triggered immediately, and the function returns 0. This correctly reflects that no rotations or button presses are required.

If a character in the key appears multiple times in the ring, the loop over letters[key[index]] evaluates each possible landing position. The algorithm therefore automatically selects the rotation that yields the smallest cumulative cost, even when the optimal choice depends on future characters.

The calculation of closest uses min(abs(rotation - i), len(ring) - abs(rotation - i)). This expression correctly handles the wrap-around scenario where rotating the opposite direction yields a shorter path, for example moving from position 1 to position len(ring)-1 on a ring of length n.

Because the recursion is memoized, the function gracefully handles cases where the same (index, rotation) state can be reached via different sequences of moves, such as when the ring contains repeated letters that lead to identical alignment after different numbers of steps.

Performance Optimizations

The most significant optimization is the use of functools.cache (or @cache) on the recursive function. By storing the result for each distinct (index, rotation) pair, the algorithm avoids recomputing the sub-problem for identical suffixes of the key and identical ring orientations. This transforms what would otherwise be an exponential search into a tractable dynamic-programming solution.

Precomputing the positions of each character in the ring eliminates the need to scan the entire ring during each recursive step. The lookup letters[key[index]] yields a ready-made list of candidate indices, reducing per-step work to a simple iteration over those candidates.

The distance calculation min(abs(rotation - i), len(ring) - abs(rotation - i)) is performed in constant time and captures both clockwise and counter-clockwise rotations without additional branching or loops.

Together, these techniques keep the number of explored states bounded by the product of the key length and the ring length, while each state is processed in time proportional to the number of occurrences of the current key character. This yields a highly efficient solution for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are playing with a giant circular toy that has letters all around its edge. There is a special secret word that you want to type, but you have to turn the circle to line up the right letter at the top, and then push a button to lock it in place.

The first part of the code acts like a helper. It runs around the circle once and writes down on a piece of paper exactly where every letter lives. If you have three letter A's, it remembers all three spots so you know where you can find them later.

Then, the code starts a game of thinking ahead. It looks at the first letter of your secret word and figures out how many steps it takes to turn the circle from where it is now to that letter. Because it is a circle, you can turn left or right to find the quickest way to get there. Once the letter is at the top, it pushes the button.

After that, it does the exact same thing for the next letter in the word. It keeps looking at where the circle stopped and figures out the best way to get to the next letter. It does this over and over again until every single letter is typed out. The code is very clever because it remembers the best paths it finds, so it does not have to worry about the same thing twice. It just keeps trying the different ways to spin the circle until it finds the smallest number of turns needed to finish the whole word.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.89 | σ = 1.26

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
gouthampradhan Java
JoshCrozier JS
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
zfang399 C++
33 links | 19 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 medium
2 solutions   March 29, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality