Palindrome Partitioning Using Backtracking in DSA Go - Time & Space Complexity
We want to understand how the time needed grows when we find all palindrome partitions of a string using backtracking.
How does the number of steps change as the string gets longer?
Analyze the time complexity of the following code snippet.
func isPalindrome(s string, start, end int) bool {
for start < end {
if s[start] != s[end] {
return false
}
start++
end--
}
return true
}
func backtrack(s string, start int, path []string, result *[][]string) {
if start == len(s) {
temp := make([]string, len(path))
copy(temp, path)
*result = append(*result, temp)
return
}
for end := start; end < len(s); end++ {
if isPalindrome(s, start, end) {
backtrack(s, end+1, append(path, s[start:end+1]), result)
}
}
}
This code finds all ways to split a string into parts where each part is a palindrome.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The backtracking recursion explores all substring splits, and for each substring, it checks if it is a palindrome.
- How many times: The recursion can explore many partitions, and palindrome checks happen for many substrings repeatedly.
As the string length grows, the number of possible palindrome partitions grows very fast because many substring combinations are possible.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Thousands of palindrome checks and recursive calls |
| 100 | Millions to billions of operations due to many partitions |
| 1000 | Operations grow extremely fast, often impractical without optimization |
Pattern observation: The work grows faster than any simple polynomial, roughly exponential with input size.
Time Complexity: O(n * 2^n)
This means the time needed grows very fast, roughly doubling with each extra character, multiplied by the cost to check palindromes.
[X] Wrong: "The algorithm runs in polynomial time because it just uses loops and recursion."
[OK] Correct: The recursion explores all possible partitions, which grow exponentially, so the time is much larger than polynomial.
Understanding this complexity helps you explain why backtracking can be slow and when to consider optimizations or pruning in real problems.
"What if we used memoization to remember palindrome checks? How would the time complexity change?"
Practice
Solution
Step 1: Understand palindrome partitioning
Palindrome partitioning means dividing a string into parts where each part is a palindrome.Step 2: Role of backtracking
Backtracking helps explore all possible ways to split the string into palindrome parts.Final Answer:
To split a string into all possible palindrome substrings -> Option DQuick Check:
Palindrome partitioning = all palindrome splits [OK]
- Confusing palindrome partitioning with finding longest palindrome
- Thinking it only finds one partition instead of all
- Mixing palindrome check with string reversal
Solution
Step 1: Analyze parameter types
The string to partition is 's string', start index is 'int', current path is '[]string', and result is pointer to slice of slices of strings.Step 2: Match correct signature
func backtrack(s string, start int, path []string, result *[][]string) matches all types correctly for backtracking palindrome partitioning.Final Answer:
func backtrack(s string, start int, path []string, result *[][]string) -> Option AQuick Check:
Correct parameter types = func backtrack(s string, start int, path []string, result *[][]string) [OK]
- Mixing parameter order or types
- Using non-pointer for result when modification needed
- Confusing path and start parameter types
package main
import "fmt"
func isPalindrome(s string) bool {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
func backtrack(s string, start int, path []string, result *[][]string) {
if start == len(s) {
temp := make([]string, len(path))
copy(temp, path)
*result = append(*result, temp)
return
}
for end := start + 1; end <= len(s); end++ {
if isPalindrome(s[start:end]) {
backtrack(s, end, append(path, s[start:end]), result)
}
}
}
func partition(s string) [][]string {
var result [][]string
backtrack(s, 0, []string{}, &result)
return result
}
func main() {
res := partition("aab")
fmt.Println(res)
}Solution
Step 1: Check palindrome substrings of "aab"
"a" is palindrome, "aa" is palindrome, "b" is palindrome, "ab" is not palindrome.Step 2: Backtracking partitions
Partitions are ["a", "a", "b"] and ["aa", "b"].Final Answer:
[["a", "a", "b"], ["aa", "b"]] -> Option AQuick Check:
All palindrome partitions = [["a", "a", "b"], ["aa", "b"]] [OK]
- Including non-palindrome substrings like "ab"
- Missing the partition with "aa"
- Returning only one partition instead of all
func isPalindrome(s string) bool {
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-i] {
return false
}
}
return true
}Solution
Step 1: Analyze index usage in palindrome check
Index s[len(s)-i] is out of range because last index is len(s)-1, not len(s).Step 2: Correct index to s[len(s)-1-i]
Subtract 1 from len(s) to avoid out of range error.Final Answer:
Index out of range error due to s[len(s)-i] -> Option CQuick Check:
Index error = Index out of range error due to s[len(s)-i] [OK]
- Using len(s)-i instead of len(s)-1-i
- Ignoring index out of range panic
- Assuming loop condition fixes index error
Solution
Step 1: Identify palindrome substrings of "racecar"
Palindromes include all single characters, "cec" (indices 2-4), "aceca" (1-5), "racecar" (0-6).Step 2: List all palindrome partitions
Partitions are: ["r", "a", "c", "e", "c", "a", "r"], ["r", "a", "cec", "a", "r"], ["r", "aceca", "r"], ["racecar"], ["r", "a", "c", "ece", "a", "r"], ["r", "a", "c", "e", "c", "a", "r"] (already counted), and others totaling 8 unique partitions.Final Answer:
8 -> Option BQuick Check:
Count all palindrome partitions = 8 [OK]
- Counting only single character partitions
- Missing longer palindrome substrings like "aceca"
- Including invalid partitions like "ece"
Ready to prove it?
Pass the test and this pattern moves unknown
