Freedom Trail

Hard Topics Company Tags

The characters of ring sit around a circular dial. Initially, ring[0] is at the selection position. Rotating the dial by one character in either direction costs one step. Pressing the selection button costs one more step and appends the selected character. Spell key in order and return the minimum total steps, including button presses. The dial keeps its position between presses, and every character in key appears in ring.

Example 1:

Freedom Trail, example 1: illustration of the example

Input: ring = "abcde"
key = "ea"

Output: 4

Explanation: Rotate one position from a to e and press, then rotate one position back to a and press again. Two rotations and two presses cost 4 steps.

Example 2:

Freedom Trail, example 2: illustration of the example

Input: ring = "abca"
key = "aa"

Output: 2

Explanation: The dial starts on a. Press twice without rotating to spell aa in 2 steps.

Example 3:

Freedom Trail, example 3: illustration of the example

Input: ring = "ab"
key = "bbb"

Output: 4

Explanation: Rotate once from a to b, then press three times. The total is 1 + 3 = 4 steps.

Constraints:

  • 1 <= ring.length, key.length <= 100
  • Both strings contain only lowercase English letters.
  • Every letter in key occurs in ring.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.