Bird
Raised Fist0
DSA Cprogramming~10 mins

Why Backtracking and What Greedy Cannot Solve in DSA C - Why It Works

Choose your learning style10 modes available
Concept Flow - Why Backtracking and What Greedy Cannot Solve
Start Problem
↓
Try Greedy Approach
↓
Check if Greedy Solution is Optimal?
No→Use Backtracking
↓
Explore All Possibilities
↓
Return Greedy Solution
↓
Choose Best Solution
↓
End
Start with greedy; if it fails to find the best answer, use backtracking to explore all options and pick the best.
Execution Sample
DSA C
int solve(int choices[], int n) {
  // Try greedy first
  int result = greedy(choices, n);
  if (!isOptimal(result)) {
    // Use backtracking
    result = backtrack(choices, n, 0, 0);
  }
  return result;
}
This code tries a greedy solution first; if it is not optimal, it uses backtracking to find the best answer.
Execution Table
StepOperationGreedy ResultBacktracking StateVisual State
1Apply greedy approachPartial solution (e.g. 7)Not startedChoices: [2,3,5], Greedy picks 5 then 2
2Check if greedy is optimal7 (not optimal)Not startedOptimal sum should be 8 (3+5) but greedy missed it
3Start backtracking7Index=0, CurrentSum=0Explore including 2
4Backtracking include 27Index=1, CurrentSum=2Explore including 3
5Backtracking include 37Index=2, CurrentSum=5Explore including 5
6Backtracking include 57Index=3, CurrentSum=10Sum exceeds target, backtrack
7Backtracking exclude 57Index=3, CurrentSum=5Backtrack to previous
8Backtracking exclude 37Index=2, CurrentSum=2Explore including 5
9Backtracking include 57Index=3, CurrentSum=7Backtrack
10Backtracking exclude 57Index=3, CurrentSum=2Backtrack
11Backtracking exclude 27Index=1, CurrentSum=0Explore including 3
12Backtracking include 37Index=2, CurrentSum=3Explore including 5
13Backtracking include 57Index=3, CurrentSum=8Found better sum 8
14Backtracking exclude 57Index=3, CurrentSum=3Backtrack
15Backtracking exclude 37Index=2, CurrentSum=0Explore including 5
16Backtracking include 57Index=3, CurrentSum=5Backtrack
17Backtracking exclude 57Index=3, CurrentSum=0Backtrack
18Backtracking complete7DoneBest sum found: 8
19Return best solution7DoneReturn 8 from backtracking
💡 Backtracking explores all subsets after greedy fails; best sum 8 found and returned.
Variable Tracker
VariableStartAfter Step 3After Step 6After Step 13Final
Greedy ResultN/A7777
Backtracking Index0033Done
Backtracking CurrentSum001088
Best Sum Found00088
Key Moments - 3 Insights
Why does greedy fail to find the best sum in this example?
Because greedy picks the largest immediate choice (5), then 2, missing the combination 3+5=8 which is better. See execution_table rows 1 and 2.
How does backtracking find the better solution?
Backtracking tries all combinations by including or excluding each choice step-by-step, exploring sums like 3+5=8. See execution_table rows 3 to 17.
Why is backtracking slower but more reliable than greedy?
Backtracking checks all possibilities to guarantee the best answer, while greedy makes quick local choices that may miss better global solutions. See variable_tracker for state changes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the greedy result and why is it not optimal?
AGreedy result is 8, which is optimal
BGreedy result is 7, but optimal sum is 8
CGreedy result is 5, which is not optimal
DGreedy result is 10, which is too large
💡 Hint
Check execution_table row 2 for greedy result and optimality check
At which step does backtracking find a better sum than greedy?
AStep 13
BStep 9
CStep 6
DStep 18
💡 Hint
Look for when CurrentSum becomes 8 in execution_table
If the greedy approach was optimal, what would happen in the code flow?
ABacktracking would run partially
BBacktracking would still run to confirm
CBacktracking would be skipped and greedy result returned
DThe program would crash
💡 Hint
Refer to concept_flow where greedy optimal check leads to either backtracking or return
Concept Snapshot
Why Backtracking and What Greedy Cannot Solve

- Greedy picks local best choices quickly
- Sometimes greedy misses global best solution
- Backtracking tries all possibilities
- Backtracking guarantees best solution but slower
- Use greedy first; if fails, use backtracking
- Backtracking explores include/exclude choices stepwise
Full Transcript
This concept explains why greedy algorithms sometimes fail to find the best solution and how backtracking solves this by exploring all possibilities. The flow starts by trying a greedy approach. If the greedy solution is not optimal, backtracking is used to explore all combinations step-by-step. The execution table shows how greedy picks a partial solution quickly but misses a better sum. Backtracking then tries including and excluding each choice, eventually finding the best sum. Variable tracking shows how the current sum and index change during backtracking. Key moments clarify why greedy fails, how backtracking works, and why backtracking is slower but more reliable. The visual quiz tests understanding of these steps. The snapshot summarizes the main points: greedy is fast but can miss the best answer, backtracking is slower but finds the best solution by checking all options.

Practice

(1/5)
1. Why is backtracking preferred over greedy algorithms in problems like the N-Queens puzzle?
easy
A. Because backtracking explores all possible solutions and can backtrack on wrong choices
B. Because greedy algorithms always find the optimal solution quickly
C. Because backtracking uses less memory than greedy algorithms
D. Because greedy algorithms do not use recursion

Solution

  1. Step 1: Understand problem requirements

    The N-Queens puzzle requires placing queens so none attack each other, needing exploration of many possibilities.
  2. Step 2: Compare algorithm approaches

    Backtracking tries all options and undoes wrong choices, while greedy picks locally best choices that may fail globally.
  3. Final Answer:

    Because backtracking explores all possible solutions and can backtrack on wrong choices -> Option A
  4. Quick Check:

    Backtracking explores all options = A [OK]
Hint: Backtracking tries all paths; greedy picks local best only [OK]
Common Mistakes:
  • Thinking greedy always finds the best solution
  • Confusing memory use between backtracking and greedy
  • Assuming backtracking is always slower without context
2. Which of the following is the correct syntax to start a backtracking function in C for solving a problem recursively?
easy
A. int backtrack[] = {0};
B. void backtrack(int step) { /* code */ }
C. backtrack() -> void { /* code */ }
D. function backtrack(int step) { /* code */ }

Solution

  1. Step 1: Identify valid C function syntax

    In C, functions are declared with return type, name, and parameters inside parentheses.
  2. Step 2: Check each option

    A matches C syntax; B is an array declaration; C and D use non-C syntax.
  3. Final Answer:

    void backtrack(int step) { /* code */ } -> Option B
  4. Quick Check:

    C function syntax = A [OK]
Hint: C functions start with return type and parentheses [OK]
Common Mistakes:
  • Using JavaScript or other language syntax in C
  • Confusing arrays with functions
  • Omitting return type in function declaration
3. Consider the following C code snippet for a backtracking approach to find subsets of {1, 2}:
void backtrack(int start, int n) {
    if (start == n) {
        printf("Reached end\n");
        return;
    }
    backtrack(start + 1, n);
    backtrack(start + 1, n);
}
int main() {
    backtrack(0, 2);
    return 0;
}
What will be the output when this code runs?
medium
A. Reached end\n
B. Reached end\nReached end\n
C. Reached end\nReached end\nReached end\nReached end\n
D. No output

Solution

  1. Step 1: Trace recursive calls

    backtrack(0,2) calls backtrack(1,2) twice; each backtrack(1,2) calls backtrack(2,2) twice.
  2. Step 2: Count base case hits

    backtrack(2,2) prints "Reached end"; it is called 4 times total (2 calls from each of 2 calls at start=1).
  3. Final Answer:

    Reached end\nReached end\nReached end\nReached end\n -> Option C
  4. Quick Check:

    4 base calls print output = A [OK]
Hint: Count recursive calls reaching base case carefully [OK]
Common Mistakes:
  • Counting only one base case print
  • Confusing number of recursive calls
  • Ignoring duplicate calls in recursion
4. The following C code attempts to solve the subset sum problem using backtracking but has a bug:
void backtrack(int index, int sum, int target, int arr[], int n) {
    if (sum == target) {
        printf("Found subset\n");
        return;
    }
    if (index == n || sum > target) {
        return;
    }
    backtrack(index + 1, sum + arr[index], target, arr, n);
    backtrack(index + 1, sum, target, arr, n);
}
int main() {
    int arr[] = {2, 4, 6};
    backtrack(0, 0, 6, arr, 3);
    return 0;
}
What is the bug in this code?
medium
A. It does not print all subsets that sum to target
B. It does not check if sum exceeds target before recursion
C. It does not handle negative numbers in array
D. It does not stop recursion after finding one subset

Solution

  1. Step 1: Analyze base case for sum == target

    When sum equals target, it prints but continues recursion because no stop condition after printing.
  2. Step 2: Identify missing stop after success

    Function returns only from current call, but parent calls continue exploring other subsets.
  3. Final Answer:

    It does not stop recursion after finding one subset -> Option D
  4. Quick Check:

    Missing stop after success = B [OK]
Hint: Stop recursion immediately after finding a valid subset [OK]
Common Mistakes:
  • Assuming printing once stops all recursion
  • Ignoring need to return from all recursive calls
  • Confusing sum checks with recursion control
5. You want to solve the problem of finding all combinations of coins that sum to a target amount. Why can't a greedy algorithm always solve this correctly, and how does backtracking help? Choose the best explanation.
hard
A. Greedy picks largest coins first which may miss combinations; backtracking tries all coin choices systematically
B. Greedy uses more memory; backtracking uses less memory
C. Greedy is slower than backtracking for coin problems
D. Backtracking only tries one coin at a time, greedy tries all

Solution

  1. Step 1: Understand greedy approach limitation

    Greedy picks largest coin repeatedly, which can miss valid combinations with smaller coins.
  2. Step 2: Understand backtracking advantage

    Backtracking tries all coin combinations by exploring all choices and backtracking on failures.
  3. Final Answer:

    Greedy picks largest coins first which may miss combinations; backtracking tries all coin choices systematically -> Option A
  4. Quick Check:

    Greedy misses combos; backtracking explores all = A [OK]
Hint: Greedy misses combos; backtracking explores all systematically [OK]
Common Mistakes:
  • Assuming greedy always finds all solutions
  • Confusing memory use with correctness
  • Thinking backtracking is always slower without context
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