Freedom Trail

Minimum steps to spell `key` by rotating a ring — DP over (key index, ring position).

Hard
Time O(R * K * R) Space O(R)
LeetCode
5 min read
dp

Problem#

A ring of characters; pointer starts at index 0. At each step, rotate one position clockwise or counter-clockwise (cost 1), or press the button (cost 1) to commit the pointed character. Spell key. Return minimum total steps.

Examples#

  • ring = "godding", key = "gd"4

Constraints#

  • 1 <= |ring|, |key| <= 100.

Approach#

DP from the end. dp[k][i] = min steps to spell key[k:] with pointer at ring index i. For each next-position j matching key[k], cost is min rotation + 1 + dp[k+1][j]. Iterate k from |key|-1 down to 0.

Solution#

Freedom Trail
class Solution {
public:
int findRotateSteps(string ring, string key) {
int R = ring.size(), K = key.size();
vector<vector<int>> positions(26);
for (int i = 0; i < R; ++i) positions[ring[i] - 'a'].push_back(i);
vector<int> dp(R, 0);
for (int k = K - 1; k >= 0; --k) {
vector<int> nd(R, INT_MAX);
for (int i = 0; i < R; ++i) {
for (int j : positions[key[k] - 'a']) {
int rot = min(abs(i - j), R - abs(i - j));
nd[i] = min(nd[i], rot + 1 + dp[j]);
}
}
dp = nd;
}
return dp[0];
}
};

Editorial#

Two-dimensional DP (k, i): which character of key are we matching next, and where is the pointer. Rotation cost is the smaller of clockwise / counter-clockwise distance — a single min. The transition tries every ring position matching key[k].

Complexity#

  • Time: O(R * K * R).
  • Space: O(R).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.