LeetCode #3441 — HARD

Minimum Cost Good Caption

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

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

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. 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);
  }
}
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.