Skip to content
Problem 514 · LeetCode 514(opens in a new tab)

Freedom Trail

HardDynamic programming

A circular dial has the letters of ring written around it, in order, and one spot at the top is the pointer. At the start, ring[0] is under the pointer. You must spell the word key letter by letter.

One step turns the dial by one position, either way round. When the next letter of key is under the pointer, pressing the button types it, and the press also costs one step. Return the fewest steps needed to type all of key.

Example 1

Input:  ring = "ddogddo", key = "og"
Output: 5
Why:    turn 2 to the o at 2, press, turn 1 to g, press
2 more examples and the constraints

Example 2

Input:  ring = "abcde", key = "eda"
Output: 7
Why:    turns 1, 1 and 2, plus 3 presses

Example 3

Input:  ring = "xyz", key = "zzz"
Output: 4
Why:    one turn to z, then three presses

Constraints

  • 1 ≤ length of ring, length of key ≤ 100
  • Both strings contain only lower-case English letters
  • Every letter of key appears somewhere in ring

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with memoO(m·n²)
  2. Bottom-up, one row per letterO(m·n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for ring and key of 100Verdict
Recursion with memoO(m·n²)
Passes; easy to derive
Bottom-up, one row per letterO(m·n²)
Best; no recursion, O(n) memory

n = length of ring, m = length of key.

Edge cases to test

  • Repeated key letter. "zzz" on "xyz": after the first z, the others cost only a press each.
  • Shorter way round. In "abcde", going from a to e is 1 step backwards, not 4 forwards.
  • First letter already on top. If key[0] = ring[0], the first letter costs just the press.
  • One-letter ring. ring = "a", key = "aaa" gives 3: presses only.

Common mistakes

  • Always turning to the nearest copy of the letter, which can cost more later.
  • Forgetting the wrap-around, so a to e in "abcde" is counted as 4 instead of 1.
  • Leaving out the press, or counting it once instead of once per key letter.

How to talk through it

  1. 1Clarify. Does a press cost a step? Can the dial turn both ways? Is every key letter on the ring?
  2. 2Show greedy fails. Use a ring where the nearest copy of a letter is far from the next one.
  3. 3Name the state. Next key index and the position at the top; nothing else affects the future.
  4. 4Code the rows. One row per key letter, filled from the previous row with circular distances.
  5. 5Test out loud. Run Example 1 and a repeated letter like "zzz".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?