#2911
Minimum Changes to Make K Semi-palindromes
HardTwo PointersStringDynamic ProgrammingDynamic ProgrammingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n^3) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n^3)Space O(n²)
The optimal approach uses dynamic programming to efficiently calculate the minimum changes needed by storing results of subproblems. This avoids redundant calculations and significantly reduces the time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[i][j] represents the minimum changes needed to partition the substring s[i:] into j parts.
- 2Step 2: Precompute the minimum changes needed to convert any substring s[i..x] into a semi-palindrome for all valid divisors.
- 3Step 3: Fill the DP table using the relation dp[i][j] = min(dp[x + 1][j - 1] + v[i][x]) for all valid x.
solution.py33 lines
1def minChanges(s, k):
2 n = len(s)
3 dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
4 v = [[0] * n for _ in range(n)]
5
6 def isSemiPalindrome(sub):
7 changes = 0
8 for d in range(1, len(sub)):
9 groups = [[] for _ in range(d)]
10 for i in range(len(sub)):
11 groups[i % d].append(sub[i])
12 changes_needed = 0
13 for group in groups:
14 count = [0] * 26
15 for char in group:
16 count[ord(char) - ord('a')] += 1
17 changes_needed += len(group) - max(count)
18 changes = min(changes, changes_needed)
19 return changes
20
21 for i in range(n):
22 for j in range(i, n):
23 v[i][j] = isSemiPalindrome(s[i:j + 1])
24
25 for i in range(n):
26 dp[i][1] = v[i][n - 1]
27
28 for j in range(2, k + 1):
29 for i in range(n):
30 for x in range(i, n):
31 dp[i][j] = min(dp[i][j], dp[x + 1][j - 1] + v[i][x])
32
33 return dp[0][k]ℹ
Complexity note: The time complexity is O(n^3) due to the nested loops for filling the DP table and calculating semi-palindrome changes, while space complexity is O(n²) for storing the DP and precomputed values.
- 1Understanding how to partition the string is crucial for minimizing changes.
- 2Precomputing semi-palindrome changes for substrings can save time in dynamic programming.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.