KatInterview

Minimum Cost to Type a String on a Circular Keyboard

Dynamic ProgrammingAuto-graded · 17 test cases
EasyAuto-gradedDynamic Programmingdynamic programmingstring DPgreedy

Last updated

Tests string DP by computing the minimum total movement cost to type a target string on a circular letter wheel, starting from a given letter.

Minimum Cost to Type a String on a Circular Keyboard

You are given a circular keyboard with the 26 lowercase English letters arranged in alphabetical order around a wheel:

a - b - c - ... - z - a - b - ...

A pointer starts at a given letter start. To type a target string, you move the pointer one step at a time — either clockwise or counter-clockwise — and each step costs 1. Once the pointer is on the desired letter, you "press" it (pressing is free).

You want to type all characters in target in order. Return the minimum total movement cost to type the entire string.

Notes

  • The wheel has exactly 26 positions. Moving from 'a' to 'z' costs 1 (they are adjacent).
  • At each character, you independently choose the cheaper direction (clockwise or counter-clockwise).
  • The pointer always ends at the last character typed.

Constraints

  • 1 <= len(target) <= 2000
  • target consists only of lowercase English letters ('a'–'z').
  • start is a single lowercase English letter ('a'–'z').

Examples

Example 1

Input: min_typing_cost('a', 'azb')

Output: 3

Example 2

Input: min_typing_cost('a', 'aaa')

Output: 0

Example 3

Input: min_typing_cost('z', 'abcde')

Output: 5

Hints

Hint 1

For each character in target, the cost to move from one letter to the next is the minimum of the clockwise distance and the counter-clockwise distance on a wheel of 26 letters.

Hint 2

The clockwise distance from letter a to letter b (by index) is (b - a) % 26, and the counter-clockwise distance is (a - b) % 26. The cost for one move is min of those two.

Hint 3

Since each character's movement cost depends only on the previous character (not any earlier history), you can solve this greedily — or with a simple DP where the state is just the current position — by summing up the minimum step costs.