4. Find the bug in this Go backtracking code snippet that tries to generate all permutations of a slice of integers:
func permute(nums []int, path []int, used []bool) {
if len(path) == len(nums) {
fmt.Println(path)
return
}
for i := 0; i < len(nums); i++ {
if used[i] {
continue
}
path = append(path, nums[i])
used[i] = true
permute(nums, path, used)
used[i] = false
}
}
medium
A. Missing removal of last element from path after recursion
B. Used slice is not initialized
C. Base case condition is incorrect
D. Loop index should start from 1
Solution
Step 1: Analyze backtracking recursion steps
After recursive call, path must remove last added element to backtrack correctly.
Step 2: Identify missing backtracking step
Code appends to path but never removes last element after recursion, causing incorrect paths.
Final Answer:
Missing removal of last element from path after recursion -> Option A
Quick Check:
Backtracking needs to undo path changes [OK]
Hint: Always undo changes to path after recursive call [OK]
Common Mistakes:
Forgetting to remove last element from path
Not initializing used slice before call
Incorrect base case length check
5. You want to solve the classic N-Queens problem where you place N queens on an NxN chessboard so that no two queens attack each other. Why can't a greedy algorithm solve this correctly, and how does backtracking help?
hard
A. Greedy only works for even N; backtracking works for all N.
B. Greedy places queens row by row without checking future conflicts; backtracking tries all placements and backtracks on conflicts.
C. Greedy uses too much memory; backtracking uses less memory by pruning.
D. Greedy sorts queens by position; backtracking sorts by attack count.
Solution
Step 1: Understand greedy limitations for N-Queens
Greedy tries to place queens row by row choosing first safe spot, but may miss solutions requiring backtracking.
Step 2: Understand backtracking approach
Backtracking tries all possible queen placements, undoing choices when conflicts arise, ensuring all solutions are found.
Final Answer:
Greedy places queens row by row without checking future conflicts; backtracking tries all placements and backtracks on conflicts. -> Option B
Quick Check:
N-Queens needs full search, not greedy local choice [OK]
Hint: N-Queens needs full search; greedy fails on future conflicts [OK]
Common Mistakes:
Thinking greedy can always find a solution
Confusing memory use differences
Believing greedy works only for even N
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.