Magicsheet logo

Minimum Cost Good Caption

Hard
100%
Updated 8/1/2025

Minimum Cost Good Caption

What is this problem about?

The Minimum Cost Good Caption problem defines a "good caption" as a string where every character belongs to a group of at least three identical consecutive characters (e.g., "aaabbb" is good, "aabbb" is not). You are given an initial string and the cost to change any character to another is the absolute difference of their alphabetical positions. You need to find the minimum cost to make the string "good" and the lexicographically smallest such string.

Why is this asked in interviews?

This is a high-difficulty Minimum Cost Good Caption interview question from TikTok and Fractal Analytics. It's a complex Dynamic Programming problem involving string manipulation and lexicographical constraints. It tests if a candidate can handle multi-faceted state transitions and meticulous back-tracking to reconstruct the optimal string.

Algorithmic pattern used

The String Dynamic Programming interview pattern with state dp[i][char][count] or similar is used.

  1. dp[i][last_char] stores the minimum cost to make the prefix of length i good, ending in last_char.
  2. A character must be part of a block of size 3\ge 3.
  3. When transitioning at index i, you can either continue the current character's block or start a new block of a different character (only if the current block is already 3\ge 3).
  4. To handle lexicographical requirements, you must carefully choose the transition when costs are equal.

Example explanation

String "aba", costs 1 per shift.

  1. "aba" is not good (no group of 3).
  2. To make it good, all 3 must be the same.
  3. Options: "aaa" (cost |b-a| = 1), "bbb" (cost |a-b| + |a-b| = 2).
  4. Minimum cost is 1, string is "aaa". For longer strings, the DP will decide where to switch from 'a's to 'b's or 'c's.

Common mistakes candidates make

  • Small block sizes: Forgetting that a block can be 4, 5, or more characters. The condition is "at least three," not "exactly three."
  • Lexicographical order: Not properly handling ties in the DP table, resulting in a correct cost but the wrong string.
  • State space: Using too much memory. Since you only care about the previous character and group size, the state can be optimized.

Interview preparation tip

When a problem asks for "minimum cost" AND "lexicographically smallest," you almost always need to store the choice you made at each step in the DP. This allows you to backtrack from the end to the start to build the result string.

Similar Questions