Hint: Check parameter types: string, int, slice, pointer to result [OK]
Common Mistakes:
Mixing parameter order or types
Using non-pointer for result when modification needed
Confusing path and start parameter types
3. What is the output of the following Go code snippet?
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)
}
medium
A. [["a", "a", "b"], ["aa", "b"]]
B. [["aab"]]
C. [["a", "ab"]]
D. [["aa", "ab"]]
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 A
Quick Check:
All palindrome partitions = [["a", "a", "b"], ["aa", "b"]] [OK]
Hint: Check all palindrome splits, ignore non-palindromes [OK]
Common Mistakes:
Including non-palindrome substrings like "ab"
Missing the partition with "aa"
Returning only one partition instead of all
4. Identify the bug in this Go backtracking code snippet for palindrome partitioning:
func isPalindrome(s string) bool {
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-i] {
return false
}
}
return true
}
medium
A. Missing return statement
B. Incorrect loop condition, should be i <= len(s)/2
C. Index out of range error due to s[len(s)-i]
D. No bug, code is correct
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 C
Quick Check:
Index error = Index out of range error due to s[len(s)-i] [OK]
Hint: Last index is len(s)-1, not len(s) [OK]
Common Mistakes:
Using len(s)-i instead of len(s)-1-i
Ignoring index out of range panic
Assuming loop condition fixes index error
5. Given the string "racecar", how many palindrome partitions will the backtracking algorithm find? Consider all possible partitions where each substring is a palindrome.
hard
A. 4
B. 8
C. 6
D. 10
Solution
Step 1: Identify palindrome substrings of "racecar"
Palindromes include all single characters, "cec" (indices 2-4), "aceca" (1-5), "racecar" (0-6).