Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Why Backtracking and What Greedy Cannot Solve in DSA Typescript - 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 Subset Sum
What is the output of the following TypeScript code that uses backtracking to find subsets summing to 5?
DSA Typescript
function backtrack(nums: number[], target: number, start: number, path: number[], res: number[][]): void {
  if (target === 0) {
    res.push([...path]);
    return;
  }
  for (let i = start; i < nums.length; i++) {
    if (nums[i] > target) continue;
    path.push(nums[i]);
    backtrack(nums, target - nums[i], i + 1, path, res);
    path.pop();
  }
}

const nums = [1, 2, 3, 4];
const res: number[][] = [];
backtrack(nums, 5, 0, [], res);
console.log(res);
A[[1,2,3],[1,4],[2,3]]
B[[1,4],[2,3]]
C[[1,4],[2,3],[5]]
D[[1,2,3,4]]
Attempts:
2 left
💡 Hint
Think about which combinations of numbers add exactly to 5 without repetition.
🧠 Conceptual
intermediate
1:30remaining
Why Greedy Fails for Subset Sum
Why does a greedy algorithm fail to solve the subset sum problem correctly in all cases?
ABecause greedy algorithms make local optimal choices that may miss the correct subset sum.
BBecause greedy algorithms always find the global optimum by checking all subsets.
CBecause greedy algorithms use backtracking to explore all possibilities.
DBecause greedy algorithms sort the input and always find the correct subset.
Attempts:
2 left
💡 Hint
Think about how greedy algorithms decide step-by-step without revisiting choices.
❓ Predict Output
advanced
2:30remaining
Backtracking vs Greedy Output Comparison
What is the output of the following TypeScript code comparing greedy and backtracking approaches for target sum 7?
DSA Typescript
function greedy(nums: number[], target: number): number[] {
  const res: number[] = [];
  let sum = 0;
  for (const num of nums) {
    if (sum + num <= target) {
      res.push(num);
      sum += num;
    }
  }
  return res;
}

function backtrack(nums: number[], target: number, start: number, path: number[], res: number[][]): void {
  if (target === 0) {
    res.push([...path]);
    return;
  }
  for (let i = start; i < nums.length; i++) {
    if (nums[i] > target) continue;
    path.push(nums[i]);
    backtrack(nums, target - nums[i], i + 1, path, res);
    path.pop();
  }
}

const nums = [2, 3, 5, 6];
const greedyResult = greedy(nums, 7);
const backtrackResult: number[][] = [];
backtrack(nums, 7, 0, [], backtrackResult);
console.log({greedyResult, backtrackResult});
A{"greedyResult":[2,3],"backtrackResult":[[2,5],[3,4]]}
B{"greedyResult":[2,3,5],"backtrackResult":[[2,5],[3,5]]}
C{"greedyResult":[2,3],"backtrackResult":[[2,5]]}
D}]]4,3[,]5,2[[:"tluseRkcartkcab",]3,2[:"tluseRydeerg"{
Attempts:
2 left
💡 Hint
Check which subsets sum exactly to 7 and what greedy picks.
🔧 Debug
advanced
2:00remaining
Identify the Error in Greedy Algorithm for Coin Change
What error does the following greedy coin change code produce when trying to make change for 6 with coins [1,3,4]?
DSA Typescript
function greedyCoinChange(coins: number[], amount: number): number[] {
  coins.sort((a, b) => b - a);
  const result: number[] = [];
  for (const coin of coins) {
    while (amount >= coin) {
      result.push(coin);
      amount -= coin;
    }
  }
  if (amount !== 0) throw new Error('Cannot make exact change');
  return result;
}

console.log(greedyCoinChange([1,3,4], 6));
AReturns [4,1,1] which sums to 6
BReturns [4,3] which sums to 7
CReturns [3,3] which sums to 6
DThrows 'Cannot make exact change' error
Attempts:
2 left
💡 Hint
Check how the greedy picks coins starting from largest.
🧠 Conceptual
expert
1:30remaining
Why Backtracking is Needed for N-Queens Problem
Why is backtracking necessary to solve the N-Queens problem instead of a greedy approach?
ABecause greedy algorithms can place queens anywhere without checking conflicts.
BBecause backtracking always places queens in the first row only.
CBecause greedy algorithms use recursion to explore all board positions.
DBecause greedy algorithms cannot guarantee placing all queens without conflicts by local choices alone.
Attempts:
2 left
💡 Hint
Think about how placing one queen affects future placements.

Practice

(1/5)
1. Why is backtracking preferred over greedy algorithms for solving problems like the N-Queens puzzle?
easy
A. Because greedy algorithms always find the optimal solution faster
B. Because backtracking explores all possible solutions and can undo choices, while greedy makes irreversible choices
C. Because backtracking uses less memory than greedy algorithms
D. Because greedy algorithms are only used for sorting problems

Solution

  1. Step 1: Understand backtracking's approach

    Backtracking tries all possible options and can go back (undo) if a choice leads to failure.
  2. Step 2: Compare with greedy approach

    Greedy algorithms make the best immediate choice but cannot undo it, so they may miss the correct solution.
  3. Final Answer:

    Because backtracking explores all possible solutions and can undo choices, while greedy makes irreversible choices -> Option B
  4. Quick Check:

    Backtracking = explores all + undo [OK]
Hint: Backtracking tries all paths; greedy picks one path only [OK]
Common Mistakes:
  • Thinking greedy always finds the best solution
  • Confusing backtracking with brute force
  • Believing backtracking uses less memory
2. Which of the following TypeScript code snippets correctly represents the start of a backtracking function signature?
easy
A. function backtrack(path number[], options number[]): void
B. function backtrack(path: number[], options: number[]) => void
C. function backtrack(path: number[], options: number[]): void
D. function backtrack(path: number[], options: number[]): number

Solution

  1. Step 1: Check TypeScript function syntax

    Correct syntax uses colon ':' to specify types and parentheses for parameters.
  2. Step 2: Verify return type and arrow usage

    function backtrack(path: number[], options: number[]): void uses correct syntax with void return type; others have syntax errors or wrong return type.
  3. Final Answer:

    function backtrack(path: number[], options: number[]): void -> Option C
  4. Quick Check:

    Correct TypeScript function syntax = function backtrack(path: number[], options: number[]): void [OK]
Hint: Look for colons and parentheses in function parameters [OK]
Common Mistakes:
  • Missing colons between parameter and type
  • Using arrow '=>' incorrectly in function signature
  • Wrong return type specified
3. Consider this TypeScript backtracking code snippet for generating subsets:
function backtrack(start: number, path: number[], nums: number[], result: number[][]) {
  result.push([...path]);
  for (let i = start; i < nums.length; i++) {
    path.push(nums[i]);
    backtrack(i + 1, path, nums, result);
    path.pop();
  }
}

const nums = [1, 2];
const result: number[][] = [];
backtrack(0, [], nums, result);
console.log(result);
What is the output printed?
medium
A. [[], [2], [1, 2], [1]]
B. [[1], [2]]
C. [[1, 2]]
D. [[], [1], [1, 2], [2]]

Solution

  1. Step 1: Trace backtracking calls with nums = [1, 2]

    Start with empty path [], add it to result. Then add 1, recurse, add [1], add 2, recurse, add [1,2], backtrack, add 2 alone, add [2].
  2. Step 2: Collect all subsets generated

    Subsets are [], [1], [1, 2], and [2] in order.
  3. Final Answer:

    [[], [1], [1, 2], [2]] -> Option D
  4. Quick Check:

    All subsets generated = [[], [1], [1, 2], [2]] [OK]
Hint: Backtracking with push/pop generates all subsets including empty [OK]
Common Mistakes:
  • Forgetting to add empty subset
  • Not popping after recursion causing wrong subsets
  • Mixing order of subsets
4. The following TypeScript backtracking code tries to find all permutations of [1, 2], but it has a bug:
function permute(nums: number[], path: number[], used: boolean[], result: number[][]) {
  if (path.length === nums.length) {
    result.push(path);
    return;
  }
  for (let i = 0; i < nums.length; i++) {
    if (used[i]) continue;
    path.push(nums[i]);
    used[i] = true;
    permute(nums, path, used, result);
    path.pop();
    used[i] = false;
  }
}

const result: number[][] = [];
permute([1, 2], [], [false, false], result);
console.log(result);
What is the bug and how to fix it?
medium
A. Bug: Pushing path directly causes reference issues; fix by pushing a copy of path
B. Bug: used array is not updated correctly; fix by removing used[i] = false
C. Bug: Base case condition is wrong; fix by changing path.length === nums.length to path.length > nums.length
D. Bug: Loop should start from 1 instead of 0; fix by changing for loop start

Solution

  1. Step 1: Identify the problem with pushing path

    Pushing path directly adds the same array reference multiple times, causing all entries to be the same final path.
  2. Step 2: Fix by pushing a copy of path

    Use result.push([...path]) to push a new array copy each time.
  3. Final Answer:

    Bug: Pushing path directly causes reference issues; fix by pushing a copy of path -> Option A
  4. Quick Check:

    Push copy of path, not reference [OK]
Hint: Always push a copy of path in backtracking results [OK]
Common Mistakes:
  • Pushing path reference instead of copy
  • Incorrect base case condition
  • Misusing used array updates
5. You want to solve the classic "Subset Sum" problem: given an array of positive integers and a target sum, find if any subset sums exactly to the target. Why can't a greedy algorithm solve this correctly in all cases, and how does backtracking help?
hard
A. Greedy fails because picking largest numbers first may miss exact sum; backtracking tries all subsets to find exact match
B. Greedy fails because it sorts the array; backtracking sorts and tries subsets
C. Greedy fails because it uses recursion; backtracking uses iteration
D. Greedy fails because it only works on sorted arrays; backtracking only works on unsorted arrays

Solution

  1. Step 1: Understand greedy approach limitation

    Greedy picks the largest numbers first, which may overshoot or miss the exact target sum.
  2. Step 2: How backtracking solves the problem

    Backtracking tries all subsets by including or excluding each number, ensuring it finds an exact sum if it exists.
  3. Final Answer:

    Greedy fails because picking largest numbers first may miss exact sum; backtracking tries all subsets to find exact match -> Option A
  4. Quick Check:

    Subset sum needs all subsets tried = Greedy fails because picking largest numbers first may miss exact sum; backtracking tries all subsets to find exact match [OK]
Hint: Subset sum needs all subsets; greedy picks only some [OK]
Common Mistakes:
  • Thinking greedy always finds exact sum
  • Confusing sorting with solving approach
  • Believing backtracking is iterative only
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