Minimum Cost Good Caption - Problem
You're working on a social media platform that validates captions for posts. A good caption is one where every character appears in groups of at least 3 consecutive occurrences.
Examples:
"aaabbb"✅ Good caption (3 a's, 3 b's)"aaaaccc"✅ Good caption (4 a's, 3 c's)"aabbb"❌ Bad caption (only 2 a's)"ccccd"❌ Bad caption (only 1 d)
You can modify any character by changing it to an adjacent alphabet character:
- Change to previous character (e.g., 'b' → 'a'), unless it's 'a'
- Change to next character (e.g., 'b' → 'c'), unless it's 'z'
Goal: Transform the caption into a good caption using the minimum number of operations. If multiple solutions exist, return the lexicographically smallest one. If impossible, return an empty string.
Input & Output
example_1.py — Basic Transformation
$
Input:
"aabcc"
›
Output:
"aaabbb"
💡 Note:
Change the last 'c' to 'b' (cost 1) and the second-to-last 'c' to 'b' (cost 1). Total cost: 2. Result: "aaabbb" with groups of 3 a's and 3 b's.
example_2.py — Lexicographically Smallest
$
Input:
"abc"
›
Output:
"aaa"
💡 Note:
Transform all characters to 'a': change 'b' to 'a' (cost 1) and 'c' to 'b' to 'a' (cost 2). Total cost: 3. "aaa" is lexicographically smaller than "bbb" or "ccc".
example_3.py — Impossible Case
$
Input:
"az"
›
Output:
""
💡 Note:
String length is 2, which is less than 3. Cannot form any groups of 3+ consecutive characters. Return empty string.
Constraints
- 1 ≤ caption.length ≤ 1000
- caption consists of only lowercase English letters
- Each group must have at least 3 consecutive identical characters
- Return lexicographically smallest result among minimum cost solutions
Visualization
Tap to expand
Understanding the Visualization
1
Identify Current Groups
Scan the string to see existing character groups
2
Plan Optimal Segmentation
Decide where to split the string into segments of 3+ characters
3
Calculate Transformation Costs
For each segment, find the cheapest character to transform all to
4
Choose Lexicographically Smallest
Among minimum cost solutions, pick the one that comes first alphabetically
Key Takeaway
🎯 Key Insight: Use dynamic programming to optimally segment the string and minimize transformation costs while ensuring lexicographic ordering.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code