Bird
Raised Fist0
DSA Goprogramming~20 mins

Why Backtracking and What Greedy Cannot Solve in DSA Go - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Backtracking Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Backtracking for Subset Sum Problem
Consider the following Go code that uses backtracking to find if there is a subset of numbers that sums to a target. What is the printed output after running this code?
DSA Go
package main
import "fmt"

func subsetSum(nums []int, target int, index int) bool {
    if target == 0 {
        return true
    }
    if target < 0 || index == len(nums) {
        return false
    }
    // Include nums[index]
    if subsetSum(nums, target-nums[index], index+1) {
        return true
    }
    // Exclude nums[index]
    return subsetSum(nums, target, index+1)
}

func main() {
    nums := []int{3, 34, 4, 12, 5, 2}
    target := 9
    if subsetSum(nums, target, 0) {
        fmt.Println("Subset found")
    } else {
        fmt.Println("No subset found")
    }
}
ANo subset found
BRuntime error
CCompilation error
DSubset found
Attempts:
2 left
💡 Hint
Think about whether any subset of nums sums exactly to 9.
❓ Predict Output
intermediate
2:00remaining
Greedy Algorithm Failure on Coin Change
What is the output of this Go code that tries to find minimum coins for amount 6 using greedy approach with coins [1, 3, 4]?
DSA Go
package main
import "fmt"

func minCoinsGreedy(coins []int, amount int) int {
    count := 0
    for i := len(coins) - 1; i >= 0; i-- {
        for amount >= coins[i] {
            amount -= coins[i]
            count++
        }
    }
    if amount != 0 {
        return -1
    }
    return count
}

func main() {
    coins := []int{1, 3, 4}
    amount := 6
    result := minCoinsGreedy(coins, amount)
    fmt.Println(result)
}
A3
B-1
C2
D1
Attempts:
2 left
💡 Hint
Greedy picks largest coin first, but is it optimal here?
🧠 Conceptual
advanced
2:00remaining
Why Backtracking is Needed Over Greedy
Which problem below cannot be solved correctly by a greedy algorithm but requires backtracking to explore all possibilities?
AFinding the minimum number of coins for amount 6 with coins [1, 3, 4]
BSorting an array of numbers in ascending order
CFinding all subsets of a set that sum to a target value
DFinding the maximum element in an array
Attempts:
2 left
💡 Hint
Think about problems where you must try many combinations.
❓ Predict Output
advanced
2:00remaining
Backtracking Path Exploration Output
What is the output of this Go code that prints all subsets of [1,2] using backtracking?
DSA Go
package main
import "fmt"

func backtrack(nums []int, index int, path []int) {
    if index == len(nums) {
        fmt.Print("Subset: ")
        for _, v := range path {
            fmt.Print(v, " ")
        }
        fmt.Println()
        return
    }
    // Include nums[index]
    backtrack(nums, index+1, append(path, nums[index]))
    // Exclude nums[index]
    backtrack(nums, index+1, path)
}

func main() {
    nums := []int{1, 2}
    backtrack(nums, 0, []int{})
}
A
Subset: 1 
Subset: 2 
Subset: 1 2 
Subset: 
B
Subset: 1 2 
Subset: 1 
Subset: 2 
Subset: 
C
Subset: 
Subset: 1 
Subset: 2 
Subset: 1 2 
D
Subset: 1 2 
Subset: 2 
Subset: 1 
Subset: 
Attempts:
2 left
💡 Hint
Backtracking includes subsets with and without each element.
🧠 Conceptual
expert
2:00remaining
Why Greedy Fails for Certain Optimization Problems
Which statement best explains why greedy algorithms fail for some problems that backtracking can solve?
AGreedy algorithms make locally optimal choices that may not lead to a global optimum, while backtracking explores all combinations.
BBacktracking algorithms are faster than greedy algorithms for all problems.
CGreedy algorithms always find the global optimum by exploring all possibilities.
DGreedy algorithms use recursion to explore all subsets, but backtracking does not.
Attempts:
2 left
💡 Hint
Consider how greedy chooses steps versus backtracking's exploration.

Practice

(1/5)
1. Why do we need backtracking instead of just using a greedy approach for some problems?
easy
A. Because backtracking only works for sorting problems.
B. Because backtracking always runs faster than greedy algorithms.
C. Because greedy algorithms use more memory than backtracking.
D. Because greedy algorithms make local choices that may not lead to the best overall solution.

Solution

  1. Step 1: Understand greedy algorithm behavior

    Greedy algorithms pick the best option at each step without reconsidering previous choices.
  2. Step 2: Understand backtracking advantage

    Backtracking tries all possibilities and can undo choices to find the best overall solution.
  3. Final Answer:

    Because greedy algorithms make local choices that may not lead to the best overall solution. -> Option D
  4. Quick Check:

    Greedy local choice ≠ global best [OK]
Hint: Backtracking explores all options; greedy picks locally best only [OK]
Common Mistakes:
  • Thinking greedy is always faster and better
  • Confusing memory use between algorithms
  • Believing backtracking is only for sorting
2. Which of the following Go code snippets correctly starts a backtracking function signature for solving a problem?
easy
A. func backtrack(path []int, choices []int) { }
B. func backtrack(path int, choices int) { }
C. func backtrack() int { }
D. func backtrack(path string) string { }

Solution

  1. Step 1: Identify typical backtracking parameters

    Backtracking usually passes the current path (partial solution) and remaining choices as slices.
  2. Step 2: Check each function signature

    func backtrack(path []int, choices []int) { } uses slices for path and choices, suitable for backtracking. Others use single values or wrong types.
  3. Final Answer:

    func backtrack(path []int, choices []int) { } -> Option A
  4. Quick Check:

    Backtracking uses slices for path and choices [OK]
Hint: Backtracking functions usually take slices for path and choices [OK]
Common Mistakes:
  • Using single int instead of slices
  • Returning values when not needed
  • Using wrong parameter types
3. What is the output of this Go code snippet that tries to solve the subset sum problem using backtracking?
package main
import "fmt"

func backtrack(nums []int, target int, start int, path []int) {
    if target == 0 {
        fmt.Println(path)
        return
    }
    for i := start; i < len(nums); i++ {
        if nums[i] > target {
            continue
        }
        backtrack(nums, target-nums[i], i+1, append(path, nums[i]))
    }
}

func main() {
    nums := []int{2, 3, 6, 7}
    backtrack(nums, 7, 0, []int{})
}
medium
A. [2 3 6] [7]
B. [2 3 7] [7]
C. [7]
D. [7] [2 3 6]

Solution

  1. Step 1: Understand the problem and code

    The code finds subsets of nums that sum to 7, using backtracking and no repeats.
  2. Step 2: Trace the backtracking calls

    Possible subsets: [7] sums to 7; [2,3,6] sums to 11 (too big), so skipped; only [7] prints.
  3. Final Answer:

    [7] -> Option C
  4. Quick Check:

    Only subset summing to 7 is [7] [OK]
Hint: Check sums carefully; skip subsets exceeding target [OK]
Common Mistakes:
  • Assuming [2 3 6] sums to 7
  • Confusing order of printed subsets
  • Ignoring the continue condition
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

  1. Step 1: Analyze backtracking recursion steps

    After recursive call, path must remove last added element to backtrack correctly.
  2. Step 2: Identify missing backtracking step

    Code appends to path but never removes last element after recursion, causing incorrect paths.
  3. Final Answer:

    Missing removal of last element from path after recursion -> Option A
  4. 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

  1. 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.
  2. Step 2: Understand backtracking approach

    Backtracking tries all possible queen placements, undoing choices when conflicts arise, ensuring all solutions are found.
  3. Final Answer:

    Greedy places queens row by row without checking future conflicts; backtracking tries all placements and backtracks on conflicts. -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard