#3441

Minimum Cost Good Caption

Hard
StringDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to track the minimum operations needed to convert each character into a good caption while ensuring the result is lexicographically smallest. By systematically checking groups of characters, we can minimize changes effectively.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array to store the minimum operations needed for each character.
  2. 2Step 2: Iterate through the string and for each character, check the previous two characters to determine if they can form a good caption.
  3. 3Step 3: Update the DP array based on the minimum operations required to convert the current character, ensuring to choose the lexicographically smallest option.
solution.py13 lines
1def min_cost_good_caption(caption):
2    n = len(caption)
3    dp = [[float('inf')] * 26 for _ in range(n)]
4    for i in range(26):
5        dp[0][i] = 0 if chr(i + 97) == caption[0] else 1
6    for i in range(1, n):
7        for j in range(26):
8            for k in range(max(0, j - 1), min(25, j + 1) + 1):
9                dp[i][j] = min(dp[i][j], dp[i - 1][k] + (0 if chr(j + 97) == caption[i] else 1))
10    min_ops = min(dp[n - 1])
11    if min_ops == float('inf'):
12        return ''
13    return ''.join(chr(i + 97) for i in range(26) if dp[n - 1][i] == min_ops)

Complexity note: This complexity is due to the single pass through the string and the limited number of character checks (26 letters), making it efficient.

  • 1A good caption requires characters to be grouped in threes.
  • 2Dynamic programming can efficiently track minimum operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.