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
Caption Transformation VisualizationOriginal: "aabcc"aabccStep 1: Extend 'a' group to 3aaab→a (cost 1)Step 2: Make remaining characters 'b' groupbc→b (cost 1)bc→b (cost 1)bResult: "aaabbb"Total cost: 2Groups: 3 a's, 3 b's ✓Each group has ≥ 3 consecutive identical characters
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.
Asked in
Google 23 Meta 18 Amazon 15 Microsoft 12
26.2K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen