Palindrome Partitioning DP Minimum Cuts in DSA C - Time & Space Complexity
We want to know how the time needed to find the minimum cuts for palindrome partitioning changes as the input string gets longer.
How does the number of steps grow when the string size increases?
Analyze the time complexity of the following code snippet.
int minCut(char* s) {
int n = strlen(s);
int cuts[n+1];
bool palindrome[n][n];
memset(palindrome, 0, sizeof(palindrome));
for (int i = 0; i <= n; i++) cuts[i] = i - 1;
for (int end = 0; end < n; end++) {
for (int start = 0; start <= end; start++) {
if (s[start] == s[end] && (end - start < 2 || palindrome[start+1][end-1])) {
palindrome[start][end] = true;
cuts[end+1] = fmin(cuts[end+1], cuts[start] + 1);
}
}
}
return cuts[n];
}
This code finds the minimum number of cuts needed to split a string into palindrome parts using dynamic programming.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops checking all substrings for palindrome property.
- How many times: Outer loop runs n times, inner loop runs up to n times, so roughly n x n = n² times.
As the string length grows, the number of substring checks grows roughly with the square of the length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 checks |
| 100 | About 10,000 checks |
| 1000 | About 1,000,000 checks |
Pattern observation: Doubling the input size roughly quadruples the work because of the nested loops.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the string length.
[X] Wrong: "The algorithm runs in linear time because it just scans the string twice."
[OK] Correct: The nested loops check all possible substrings, which is much more work than just scanning once or twice.
Understanding this time complexity helps you explain how dynamic programming improves over brute force and shows your skill in analyzing nested loops.
"What if we used a different method to check palindromes in constant time? How would the time complexity change?"