You are given a string caption of length n. A good caption is a string where every character appears in groups of at least 3 consecutive occurrences.
For example:
"aaabbb" and "aaaaccc" are good captions.
"aabbb" and "ccccd" are not good captions.
You can perform the following operation any number of times:
Choose an index i (where 0 <= i < n) and change the character at that index to either:
The character immediately before it in the alphabet (if caption[i] != 'a').
The character immediately after it in the alphabet (if caption[i] != 'z').
Your task is to convert the given caption into a good caption using the minimum number of operations, and return it. If there are multiple possible good captions, return the lexicographically smallest one among them. If it is impossible to create a good caption, return an empty string "".
Example 1:
Input:caption = "cdcd"
Output:"cccc"
Explanation:
It can be shown that the given caption cannot be transformed into a good caption with fewer than 2 operations. The possible good captions that can be created using exactly 2 operations are:
"dddd": Change caption[0] and caption[2] to their next character 'd'.
"cccc": Change caption[1] and caption[3] to their previous character 'c'.
Since "cccc" is lexicographically smaller than "dddd", return "cccc".
Example 2:
Input:caption = "aca"
Output:"aaa"
Explanation:
It can be proven that the given caption requires at least 2 operations to be transformed into a good caption. The only good caption that can be obtained with exactly 2 operations is as follows:
Operation 1: Change caption[1] to 'b'. caption = "aba".
Operation 2: Change caption[1] to 'a'. caption = "aaa".
Thus, return "aaa".
Example 3:
Input:caption = "bc"
Output:""
Explanation:
It can be shown that the given caption cannot be converted to a good caption by using any number of operations.
Constraints:
1 <= caption.length <= 5 * 104
caption consists only of lowercase English letters.
Problem summary: You are given a string caption of length n. A good caption is a string where every character appears in groups of at least 3 consecutive occurrences. For example: "aaabbb" and "aaaaccc" are good captions. "aabbb" and "ccccd" are not good captions. You can perform the following operation any number of times: Choose an index i (where 0 <= i < n) and change the character at that index to either: The character immediately before it in the alphabet (if caption[i] != 'a'). The character immediately after it in the alphabet (if caption[i] != 'z'). Your task is to convert the given caption into a good caption using the minimum number of operations, and return it. If there are multiple possible good captions, return the lexicographically smallest one among them. If it is impossible to create a good caption, return an empty string "".
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"cdcd"
Example 2
"aca"
Example 3
"bc"
Step 02
Core Insight
What unlocks the optimal approach
Construct a DP table and try all possible characters at every index.
Choose characters greedily to get the lexicographically smallest caption.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3441: Minimum Cost Good Caption
class Solution {
public String minCostGoodCaption(String caption) {
final int n = caption.length();
if (n < 3)
return "";
final int MAX_COST = 1_000_000_000;
int[][][] dp = new int[n][26][3];
Arrays.stream(dp).forEach(A -> Arrays.stream(A).forEach(B -> Arrays.fill(B, MAX_COST)));
// dp[i][j][k] := the minimum cost of caption[i..n - 1], where j is the last
// letter used, and k is the count of consecutive letters
for (char c = 'a'; c <= 'z'; ++c)
dp[n - 1][c - 'a'][0] = Math.abs(caption.charAt(n - 1) - c);
int minCost = MAX_COST;
for (int i = n - 2; i >= 0; --i) {
int newMinCost = MAX_COST;
for (char c = 'a'; c <= 'z'; ++c) {
final int j = c - 'a';
final int changeCost = Math.abs(caption.charAt(i) - c);
dp[i][j][0] = changeCost + minCost;
dp[i][j][1] = changeCost + dp[i + 1][j][0];
dp[i][j][2] = changeCost + Math.min(dp[i + 1][j][1], dp[i + 1][j][2]);
newMinCost = Math.min(newMinCost, dp[i][j][2]);
}
minCost = newMinCost;
}
// Reconstruct the string.
StringBuilder sb = new StringBuilder();
int cost = MAX_COST;
int letter = -1;
// Find the initial best letter.
for (int c = 25; c >= 0; --c)
if (dp[0][c][2] <= cost) {
letter = c;
cost = dp[0][c][2];
}
// Add the initial triplet.
cost -= appendLetter(caption, 0, (char) ('a' + letter), sb);
cost -= appendLetter(caption, 1, (char) ('a' + letter), sb);
cost -= appendLetter(caption, 2, (char) ('a' + letter), sb);
// Build the rest of the string.
for (int i = 3; i < n;) {
// Check if we should switch to a new letter.
final int nextLetter = getNextLetter(dp, i, cost);
if (nextLetter < letter || Arrays.stream(dp[i][letter]).min().getAsInt() > cost) {
letter = nextLetter;
cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
cost -= appendLetter(caption, i + 1, (char) ('a' + letter), sb);
cost -= appendLetter(caption, i + 2, (char) ('a' + letter), sb);
i += 3;
} else {
cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
i += 1;
}
}
return sb.toString();
}
private int getNextLetter(int[][][] dp, int i, int cost) {
int nextLetter = 26;
for (int c = 25; c >= 0; --c)
if (cost == dp[i][c][2])
nextLetter = c;
return nextLetter;
}
private int appendLetter(String caption, int i, char letter, StringBuilder sb) {
sb.append(letter);
return Math.abs(caption.charAt(i) - letter);
}
}
// Accepted solution for LeetCode #3441: Minimum Cost Good Caption
package main
import (
"bytes"
"math"
"slices"
)
// https://space.bilibili.com/206214
func minCostGoodCaption(s string) string {
n := len(s)
if n < 3 {
return ""
}
f := make([]int, n+1)
f[n-1], f[n-2] = math.MaxInt/2, math.MaxInt/2
t := make([]byte, n+1)
size := make([]uint8, n)
for i := n - 3; i >= 0; i-- {
sub := []byte(s[i : i+3])
slices.Sort(sub)
a, b, c := sub[0], sub[1], sub[2]
s3 := int(t[i+3])
res := f[i+3] + int(c-a)
mask := int(b)<<24 | s3<<16 | s3<<8 | s3 // 4 个 byte 压缩成一个 int,方便比较字典序
size[i] = 3
if i+4 <= n {
sub := []byte(s[i : i+4])
slices.Sort(sub)
a, b, c, d := sub[0], sub[1], sub[2], sub[3]
s4 := int(t[i+4])
res4 := f[i+4] + int(c-a+d-b)
mask4 := int(b)<<24 | int(b)<<16 | s4<<8 | s4
if res4 < res || res4 == res && mask4 < mask {
res, mask = res4, mask4
size[i] = 4
}
}
if i+5 <= n {
sub := []byte(s[i : i+5])
slices.Sort(sub)
a, b, c, d, e := sub[0], sub[1], sub[2], sub[3], sub[4]
res5 := f[i+5] + int(d-a+e-b)
mask5 := int(c)<<24 | int(c)<<16 | int(c)<<8 | int(t[i+5])
if res5 < res || res5 == res && mask5 < mask {
res, mask = res5, mask5
size[i] = 5
}
}
f[i] = res
t[i] = byte(mask >> 24)
}
ans := make([]byte, 0, n)
for i := 0; i < n; i += int(size[i]) {
ans = append(ans, bytes.Repeat([]byte{t[i]}, int(size[i]))...)
}
return string(ans)
}
func minCostGoodCaption3(s string) string {
n := len(s)
if n < 3 {
return ""
}
f := make([]int, n+1)
f[n-1], f[n-2] = math.MaxInt/2, math.MaxInt/2
t := make([]byte, n+1)
size := make([]uint8, n)
for i := n - 3; i >= 0; i-- {
sub := []byte(s[i : i+3])
slices.Sort(sub)
a, b, c := sub[0], sub[1], sub[2]
s3 := int(t[i+3])
res := []int{f[i+3] + int(c-a), int(b), s3, s3, s3}
size[i] = 3
if i+4 <= n {
sub := []byte(s[i : i+4])
slices.Sort(sub)
a, b, c, d := sub[0], sub[1], sub[2], sub[3]
s4 := int(t[i+4])
tp := []int{f[i+4] + int(c-a+d-b), int(b), int(b), s4, s4}
if slices.Compare(tp, res) < 0 {
res = tp
size[i] = 4
}
}
if i+5 <= n {
sub := []byte(s[i : i+5])
slices.Sort(sub)
a, b, c, d, e := sub[0], sub[1], sub[2], sub[3], sub[4]
tp := []int{f[i+5] + int(d-a+e-b), int(c), int(c), int(c), int(t[i+5])}
if slices.Compare(tp, res) < 0 {
res = tp
size[i] = 5
}
}
f[i] = res[0]
t[i] = byte(res[1])
}
ans := make([]byte, 0, n)
for i := 0; i < n; i += int(size[i]) {
ans = append(ans, bytes.Repeat([]byte{t[i]}, int(size[i]))...)
}
return string(ans)
}
func minCostGoodCaption2(s string) string {
n := len(s)
if n < 3 {
return ""
}
f := make([][26]int, n+1)
minJ := make([]int, n+1)
nxt := make([][26]int, n+1)
for i := n - 1; i >= 0; i-- {
mn := math.MaxInt
for j := 0; j < 26; j++ {
res := f[i+1][j] + abs(int(s[i]-'a')-j)
res2 := math.MaxInt
if i <= n-6 {
res2 = f[i+3][minJ[i+3]] + abs(int(s[i]-'a')-j) + abs(int(s[i+1]-'a')-j) + abs(int(s[i+2]-'a')-j)
}
if res2 < res || res2 == res && minJ[i+3] < j {
res = res2
nxt[i][j] = minJ[i+3]
} else {
nxt[i][j] = j
}
f[i][j] = res
if res < mn {
mn = res
minJ[i] = j
}
}
}
ans := make([]byte, n)
i, j := 0, minJ[0]
for i < n {
ans[i] = 'a' + byte(j)
k := nxt[i][j]
if k == j {
i++
} else {
ans[i+1] = ans[i]
ans[i+2] = ans[i]
i += 3
j = k
}
}
return string(ans)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func minCostGoodCaption1(s string) string {
n := len(s)
if n < 3 {
return ""
}
memo := make([][27]int, n)
from := make([][27]int, n)
for i := range memo {
for j := range memo[i] {
memo[i][j] = -1
}
}
var dfs func(int, int) int
dfs = func(i, j int) (res int) {
if i == n {
return
}
p := &memo[i][j]
if *p != -1 {
return *p
}
defer func() { *p = res }()
x := int(s[i] - 'a')
if i > n-3 {
from[i][j] = j
return dfs(i+1, j) + abs(x-j)
}
res = math.MaxInt
for k := range 26 {
var r int
if k == j {
r = dfs(i+1, k) + abs(x-k)
} else {
r = dfs(i+3, k) + abs(x-k) + abs(int(s[i+1]-'a')-k) + abs(int(s[i+2]-'a')-k)
}
if r < res {
res = r
from[i][j] = k
}
}
return
}
dfs(0, 26)
ans := make([]byte, n)
i, j := 0, 26
for i < n {
k := from[i][j]
ans[i] = 'a' + byte(k)
if k == j {
i++
} else {
ans[i+1] = ans[i]
ans[i+2] = ans[i+1]
i += 3
j = k
}
}
return string(ans)
}
# Accepted solution for LeetCode #3441: Minimum Cost Good Caption
class Solution:
def minCostGoodCaption(self, caption: str) -> str:
n = len(caption)
if n < 3:
return ''
MAX_COST = 1_000_000_000
# dp[i][j][k] := the minimum cost of caption[i..n - 1], where j is the last
# letter used, and k is the count of consecutive letters
dp = [[[MAX_COST] * 3 for _ in range(26)] for _ in range(n)]
for c in range(26):
dp[-1][c][0] = abs(string.ascii_lowercase.index(caption[-1]) - c)
minCost = MAX_COST
for i in range(n - 2, -1, -1):
newMinCost = MAX_COST
for c in range(26):
changeCost = abs(string.ascii_lowercase.index(caption[i]) - c)
dp[i][c][0] = changeCost + minCost
dp[i][c][1] = changeCost + dp[i + 1][c][0]
dp[i][c][2] = changeCost + min(dp[i + 1][c][1], dp[i + 1][c][2])
newMinCost = min(newMinCost, dp[i][c][2])
minCost = newMinCost
# Reconstruct the string.
ans = []
cost = MAX_COST
letter = -1
# Find the initial best letter.
for c in range(25, -1, -1):
if dp[0][c][2] <= cost:
letter = c
cost = dp[0][c][2]
# Add the initial triplet.
cost -= self._appendLetter(caption, 0, chr(ord('a') + letter), ans)
cost -= self._appendLetter(caption, 1, chr(ord('a') + letter), ans)
cost -= self._appendLetter(caption, 2, chr(ord('a') + letter), ans)
# Build the rest of the string.
i = 3
while i < n:
nextLetter = self._getNextLetter(dp, i, cost)
if nextLetter < letter or min(dp[i][letter]) > cost:
letter = nextLetter
cost -= self._appendLetter(caption, i, chr(ord('a') + letter), ans)
cost -= self._appendLetter(caption, i + 1, chr(ord('a') + letter), ans)
cost -= self._appendLetter(caption, i + 2, chr(ord('a') + letter), ans)
i += 3
else:
cost -= self._appendLetter(caption, i, chr(ord('a') + letter), ans)
i += 1
return ''.join(ans)
def _getNextLetter(self, dp: list[list[list[int]]], i: int, cost: int) -> int:
nextLetter = 26
for c in range(25, -1, -1):
if cost == dp[i][c][2]:
nextLetter = c
return nextLetter
def _appendLetter(
self,
caption: str,
i: int,
letter: str,
ans: list[str]
) -> int:
ans.append(letter)
return abs(ord(caption[i]) - ord(letter))
// Accepted solution for LeetCode #3441: Minimum Cost Good Caption
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3441: Minimum Cost Good Caption
// class Solution {
// public String minCostGoodCaption(String caption) {
// final int n = caption.length();
// if (n < 3)
// return "";
//
// final int MAX_COST = 1_000_000_000;
// int[][][] dp = new int[n][26][3];
// Arrays.stream(dp).forEach(A -> Arrays.stream(A).forEach(B -> Arrays.fill(B, MAX_COST)));
// // dp[i][j][k] := the minimum cost of caption[i..n - 1], where j is the last
// // letter used, and k is the count of consecutive letters
// for (char c = 'a'; c <= 'z'; ++c)
// dp[n - 1][c - 'a'][0] = Math.abs(caption.charAt(n - 1) - c);
//
// int minCost = MAX_COST;
// for (int i = n - 2; i >= 0; --i) {
// int newMinCost = MAX_COST;
// for (char c = 'a'; c <= 'z'; ++c) {
// final int j = c - 'a';
// final int changeCost = Math.abs(caption.charAt(i) - c);
// dp[i][j][0] = changeCost + minCost;
// dp[i][j][1] = changeCost + dp[i + 1][j][0];
// dp[i][j][2] = changeCost + Math.min(dp[i + 1][j][1], dp[i + 1][j][2]);
// newMinCost = Math.min(newMinCost, dp[i][j][2]);
// }
// minCost = newMinCost;
// }
//
// // Reconstruct the string.
// StringBuilder sb = new StringBuilder();
// int cost = MAX_COST;
// int letter = -1;
//
// // Find the initial best letter.
// for (int c = 25; c >= 0; --c)
// if (dp[0][c][2] <= cost) {
// letter = c;
// cost = dp[0][c][2];
// }
//
// // Add the initial triplet.
// cost -= appendLetter(caption, 0, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, 1, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, 2, (char) ('a' + letter), sb);
//
// // Build the rest of the string.
// for (int i = 3; i < n;) {
// // Check if we should switch to a new letter.
// final int nextLetter = getNextLetter(dp, i, cost);
// if (nextLetter < letter || Arrays.stream(dp[i][letter]).min().getAsInt() > cost) {
// letter = nextLetter;
// cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, i + 1, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, i + 2, (char) ('a' + letter), sb);
// i += 3;
// } else {
// cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
// i += 1;
// }
// }
//
// return sb.toString();
// }
//
// private int getNextLetter(int[][][] dp, int i, int cost) {
// int nextLetter = 26;
// for (int c = 25; c >= 0; --c)
// if (cost == dp[i][c][2])
// nextLetter = c;
// return nextLetter;
// }
//
// private int appendLetter(String caption, int i, char letter, StringBuilder sb) {
// sb.append(letter);
// return Math.abs(caption.charAt(i) - letter);
// }
// }
// Accepted solution for LeetCode #3441: Minimum Cost Good Caption
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3441: Minimum Cost Good Caption
// class Solution {
// public String minCostGoodCaption(String caption) {
// final int n = caption.length();
// if (n < 3)
// return "";
//
// final int MAX_COST = 1_000_000_000;
// int[][][] dp = new int[n][26][3];
// Arrays.stream(dp).forEach(A -> Arrays.stream(A).forEach(B -> Arrays.fill(B, MAX_COST)));
// // dp[i][j][k] := the minimum cost of caption[i..n - 1], where j is the last
// // letter used, and k is the count of consecutive letters
// for (char c = 'a'; c <= 'z'; ++c)
// dp[n - 1][c - 'a'][0] = Math.abs(caption.charAt(n - 1) - c);
//
// int minCost = MAX_COST;
// for (int i = n - 2; i >= 0; --i) {
// int newMinCost = MAX_COST;
// for (char c = 'a'; c <= 'z'; ++c) {
// final int j = c - 'a';
// final int changeCost = Math.abs(caption.charAt(i) - c);
// dp[i][j][0] = changeCost + minCost;
// dp[i][j][1] = changeCost + dp[i + 1][j][0];
// dp[i][j][2] = changeCost + Math.min(dp[i + 1][j][1], dp[i + 1][j][2]);
// newMinCost = Math.min(newMinCost, dp[i][j][2]);
// }
// minCost = newMinCost;
// }
//
// // Reconstruct the string.
// StringBuilder sb = new StringBuilder();
// int cost = MAX_COST;
// int letter = -1;
//
// // Find the initial best letter.
// for (int c = 25; c >= 0; --c)
// if (dp[0][c][2] <= cost) {
// letter = c;
// cost = dp[0][c][2];
// }
//
// // Add the initial triplet.
// cost -= appendLetter(caption, 0, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, 1, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, 2, (char) ('a' + letter), sb);
//
// // Build the rest of the string.
// for (int i = 3; i < n;) {
// // Check if we should switch to a new letter.
// final int nextLetter = getNextLetter(dp, i, cost);
// if (nextLetter < letter || Arrays.stream(dp[i][letter]).min().getAsInt() > cost) {
// letter = nextLetter;
// cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, i + 1, (char) ('a' + letter), sb);
// cost -= appendLetter(caption, i + 2, (char) ('a' + letter), sb);
// i += 3;
// } else {
// cost -= appendLetter(caption, i, (char) ('a' + letter), sb);
// i += 1;
// }
// }
//
// return sb.toString();
// }
//
// private int getNextLetter(int[][][] dp, int i, int cost) {
// int nextLetter = 26;
// for (int c = 25; c >= 0; --c)
// if (cost == dp[i][c][2])
// nextLetter = c;
// return nextLetter;
// }
//
// private int appendLetter(String caption, int i, char letter, StringBuilder sb) {
// sb.append(letter);
// return Math.abs(caption.charAt(i) - letter);
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.