Skip to main content

Minimum Cost Good Caption - Solution & Explanation

HardStringDynamic Programming4 min readAsked at: Fractal Analytics, Tiktok
Practice this 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.

Approach Overview

Problem Overview: You are given a caption string and a cost model for modifying characters. The goal is to transform the caption into a good caption while minimizing the total modification cost. The constraint that defines a good caption applies to consecutive characters, so every position you choose affects the validity of the following positions.

Approach 1: Brute Force Enumeration (Exponential Time, Exponential Space)

Generate all possible captions by replacing each character with any of the 26 lowercase letters. For every generated string, check whether it satisfies the good caption constraint and compute the total cost of modifications. Keep the minimum cost across all valid candidates. This approach explores 26^n possibilities and becomes infeasible even for moderate n. It is mainly useful to understand the structure of the problem before introducing optimization.

Approach 2: Dynamic Programming on Character States (O(n · 26 · 2) time, O(26 · 2) space)

The key observation is that the validity of the caption depends only on the most recent characters. Instead of generating full strings, track states that represent the last chosen character and how many times it has appeared consecutively. For each index i, iterate through all candidate letters a–z. Transition from previous states while enforcing the constraint on consecutive characters. The cost of choosing a letter is the modification cost between the original character and the chosen one. This forms a classic dynamic programming transition where each step depends only on the previous index.

The DP state can be defined as dp[i][c][k], meaning the minimum cost to build a valid caption up to index i, ending with character c repeated k consecutive times. When the next character is different, the consecutive counter resets. When it is the same, ensure the constraint is not violated before extending the run. Because only the previous position matters, you can compress the DP to two layers and reduce memory usage.

This approach relies heavily on efficient iteration over characters and careful state transitions. It’s a standard pattern in string problems where local constraints propagate through the sequence. The optimization works because the number of states remains small (26 letters and a small consecutive count).

Recommended for interviews: The dynamic programming state-transition approach is what interviewers expect. Starting with brute force shows you understand the search space, but recognizing that only the previous character state matters demonstrates strong DP intuition and the ability to reduce exponential problems to linear scans.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(26^n)O(26^n)Conceptual understanding of all possible captions; not practical for real constraints
Dynamic Programming on Character StatesO(n · 26 · 2)O(26 · 2)General optimal solution when constraints depend on consecutive characters

Video Solution

Minimum Cost Good Caption (Leetcode Biweekly 149)Soumya Bhattacharjee652 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Minimum Cost Good Caption easy or hard?
Minimum Cost Good Caption is categorized as Hard because it combines string processing with state-based dynamic programming. Recognizing the correct DP state and optimizing transitions is the main challenge.
Minimum Cost Good Caption Python/Java solution
The solution typically implements dynamic programming with nested loops over the string and alphabet characters. Python, Java, C++, and Go implementations maintain DP states for the previous index and update them while computing modification costs.
How to solve Minimum Cost Good Caption in O(n)?
Use dynamic programming with a limited state representing the last chosen character and its consecutive frequency. At each index, compute the cost of assigning every possible character while respecting the caption constraint. Since the alphabet size is fixed (26), the complexity behaves like O(n).
What is the best approach for Minimum Cost Good Caption?
The most efficient approach uses dynamic programming over character states. For each position, track the previous character and how many times it has appeared consecutively, then compute the minimum cost transition. This reduces the search space to O(n · 26 · 2) time and small constant space.
Is Minimum Cost Good Caption asked at Google/Amazon/Meta?
Problems involving constrained string transformations and dynamic programming frequently appear in interviews at companies like Google, Amazon, and Meta. Variants that track consecutive characters or minimize edit cost are common interview patterns.
What data structure is used in Minimum Cost Good Caption?
The core data structure is a dynamic programming table that stores minimum costs for each state defined by the last character and its consecutive count. Arrays or hash maps can store these states efficiently during iteration.
What is the time complexity of Minimum Cost Good Caption?
The optimal dynamic programming solution runs in O(n · 26 · 2) time. For each index in the string, you evaluate transitions for 26 possible characters and a small number of consecutive states, which keeps the algorithm effectively linear in practice.

Ready to solve this problem?

Practice Minimum Cost Good Caption with our built-in code editor and test cases.

Practice on FleetCode