Bird
Raised Fist0
DSA Typescriptprogramming

Backtracking Concept and Decision Tree Visualization in DSA Typescript

Choose your learning style10 modes available
Mental Model
Backtracking tries choices one by one and goes back if a choice leads to a dead end.
Analogy: Imagine walking in a maze and choosing paths. If a path is blocked, you return to the last junction and try a different path.
Start
  ↓
Choice 1 -> Dead end
  ↓
Backtrack ← Choice 2 -> Success
Dry Run Walkthrough
Input: Find all subsets of [1, 2] using backtracking
Goal: Generate all possible subsets by choosing or skipping each element
Step 1: Start with empty subset [] at index 0
[] ↑ (index 0)
Why: We begin with no elements chosen
Step 2: Choose element 1, subset becomes [1], move to index 1
[1] ↑ (index 1)
Why: Try including first element
Step 3: Choose element 2, subset becomes [1, 2], move to index 2 (end)
[1, 2] ↑ (index 2)
Why: Try including second element
Step 4: Reached end, record subset [1, 2], backtrack to index 1
[1, 2] (recorded), back to [1] ↑ (index 1)
Why: Save current subset and try skipping element 2
Step 5: Skip element 2, subset stays [1], move to index 2 (end)
[1] ↑ (index 2)
Why: Try skipping second element
Step 6: Reached end, record subset [1], backtrack to index 0
[1] (recorded), back to [] ↑ (index 0)
Why: Save current subset and try skipping element 1
Step 7: Skip element 1, subset stays [], move to index 1
[] ↑ (index 1)
Why: Try skipping first element
Step 8: Choose element 2, subset becomes [2], move to index 2 (end)
[2] ↑ (index 2)
Why: Try including second element after skipping first
Step 9: Reached end, record subset [2], backtrack to index 1
[2] (recorded), back to [] ↑ (index 1)
Why: Save current subset and try skipping element 2
Step 10: Skip element 2, subset stays [], move to index 2 (end)
[] ↑ (index 2)
Why: Try skipping second element
Step 11: Reached end, record subset [], backtrack complete
[] (recorded)
Why: Save empty subset, all choices tried
Result:
All subsets recorded: []
[1]
[1, 2]
[2]
Annotated Code
DSA Typescript
class Backtracking {
  subsets(nums: number[]): number[][] {
    const result: number[][] = [];
    const subset: number[] = [];

    function backtrack(index: number) {
      if (index === nums.length) {
        result.push([...subset]); // record current subset
        return;
      }

      // Choose nums[index]
      subset.push(nums[index]);
      backtrack(index + 1); // move to next element

      // Backtrack: remove last choice
      subset.pop();

      // Skip nums[index]
      backtrack(index + 1); // move to next element
    }

    backtrack(0);
    return result;
  }
}

const bt = new Backtracking();
const input = [1, 2];
const output = bt.subsets(input);
for (const s of output) {
  console.log(s);
}
if (index === nums.length) { result.push([...subset]); return; }
record current subset when reached end of array
subset.push(nums[index]); backtrack(index + 1);
choose current element and move forward
subset.pop();
undo choice to try skipping element
backtrack(index + 1);
skip current element and move forward
OutputSuccess
[1, 2] [1] [2] []
Complexity Analysis
Time: O(2^n) because each element has two choices: include or skip, leading to 2^n subsets
Space: O(n) for recursion stack and subset storage during backtracking
vs Alternative: Compared to iterative subset generation, backtracking is more intuitive and easier to extend for constraints but has similar exponential time
Edge Cases
empty input array
returns [[]] as the only subset
DSA Typescript
if (index === nums.length) { result.push([...subset]); return; }
single element array
returns subsets with and without the element
DSA Typescript
subset.push(nums[index]); backtrack(index + 1);
When to Use This Pattern
When you see a problem asking for all combinations or subsets and need to explore choices step-by-step, use backtracking to try options and undo them if needed.
Common Mistakes
Mistake: Not undoing the choice (missing subset.pop()), causing wrong subsets
Fix: Add subset.pop() after recursive call to backtrack to remove last choice
Mistake: Recording subsets before reaching the end of array
Fix: Only record subsets when index reaches nums.length
Summary
Backtracking tries all choices by exploring and undoing decisions to find all solutions.
Use it when you need to explore all combinations or permutations with constraints.
The key is to choose, explore deeper, then undo the choice to try other options.

Practice

(1/5)
1. What is the main idea behind backtracking in algorithms?
easy
A. Try all possible options and undo choices when they lead to dead ends
B. Sort data before processing it
C. Use loops to repeat actions without conditions
D. Store data in a fixed-size array

Solution

  1. Step 1: Understand backtracking approach

    Backtracking tries all possible choices step-by-step and goes back if a choice fails.
  2. Step 2: Compare options with backtracking definition

    Only Try all possible options and undo choices when they lead to dead ends describes trying options and undoing wrong choices, which is backtracking.
  3. Final Answer:

    Try all possible options and undo choices when they lead to dead ends -> Option A
  4. Quick Check:

    Backtracking = Try and undo choices [OK]
Hint: Backtracking means try, fail, undo, and try again [OK]
Common Mistakes:
  • Confusing backtracking with sorting
  • Thinking backtracking is just looping
  • Believing backtracking stores fixed data only
2. Which of the following is the correct TypeScript function signature for a backtracking function that tries to build a string path?
easy
A. function backtrack(path: number): string
B. function backtrack(path: string): void
C. function backtrack(): number[]
D. function backtrack(path: boolean): boolean

Solution

  1. Step 1: Identify expected input and output

    Backtracking often builds a path string and does not return a value, so void return is common.
  2. Step 2: Match signature with backtracking pattern

    function backtrack(path: string): void matches a function taking a string path and returning void, which fits backtracking.
  3. Final Answer:

    function backtrack(path: string): void -> Option B
  4. Quick Check:

    Backtracking function signature = string input, void output [OK]
Hint: Backtracking functions usually return void and take current path [OK]
Common Mistakes:
  • Using wrong return types like number or boolean
  • Missing input parameter for current path
  • Confusing return type with output data
3. Consider this TypeScript backtracking snippet:
function backtrack(path: string, choices: string[]): void {
  if (path.length === 2) {
    console.log(path);
    return;
  }
  for (const choice of choices) {
    backtrack(path + choice, choices);
  }
}
backtrack('', ['A', 'B']);

What will be printed?
medium
A. AA, AB, BA, BB
B. A, B
C. AB, BA
D. AA, BB

Solution

  1. Step 1: Understand recursion and stopping condition

    The function prints when path length is 2, building strings by adding 'A' or 'B'.
  2. Step 2: Trace all paths of length 2

    Starting empty, choices add 'A' or 'B' twice: 'AA', 'AB', 'BA', 'BB' are printed.
  3. Final Answer:

    AA, AB, BA, BB -> Option A
  4. Quick Check:

    All 2-length combos of A and B printed [OK]
Hint: Count all 2-letter combos from choices [OK]
Common Mistakes:
  • Printing only single letters
  • Missing some combinations
  • Confusing order of printed strings
4. This backtracking code tries to generate all subsets of [1, 2] but has a bug:
function backtrack(start: number, path: number[], nums: number[]) {
  console.log(path);
  for (let i = start; i < nums.length; i++) {
    path.push(nums[i]);
    backtrack(i, path, nums);
    path.pop();
  }
}
backtrack(0, [], [1, 2]);

What is the bug?
medium
A. start should be initialized to 1
B. path.pop() is missing to undo choice
C. Console.log should be after the loop
D. Recursive call should use i + 1 instead of i to avoid duplicates

Solution

  1. Step 1: Analyze recursive call parameter

    The call uses backtrack(i, ...) which reuses the same index, causing repeated subsets.
  2. Step 2: Fix recursion to avoid duplicates

    Changing to backtrack(i + 1, ...) moves forward, preventing duplicates and infinite loops.
  3. Final Answer:

    Recursive call should use i + 1 instead of i to avoid duplicates -> Option D
  4. Quick Check:

    Advance index in recursion = i + 1 [OK]
Hint: Use i + 1 in recursion to move forward [OK]
Common Mistakes:
  • Not advancing index causing infinite recursion
  • Removing path.pop() causing wrong subsets
  • Misplacing console.log outside recursion
5. You want to use backtracking to find all 3-letter strings from letters ['X', 'Y', 'Z'] but without repeating the same letter consecutively. Which change to this code snippet enforces that?
function backtrack(path: string, letters: string[]) {
  if (path.length === 3) {
    console.log(path);
    return;
  }
  for (const letter of letters) {
    // What condition to add here?
    backtrack(path + letter, letters);
  }
}
backtrack('', ['X', 'Y', 'Z']);
hard
A. Add: if (path.length < 3) before recursive call
B. Add: if (letter !== 'X') before recursive call
C. Add: if (path.length === 0 || path[path.length - 1] !== letter) before recursive call
D. Add: if (path.includes(letter)) before recursive call

Solution

  1. Step 1: Understand the no consecutive repeat rule

    We must skip adding a letter if it matches the last letter in path.
  2. Step 2: Write condition to check last letter

    Condition if path is empty or last letter differs from current letter ensures no repeats.
  3. Final Answer:

    Add: if (path.length === 0 || path[path.length - 1] !== letter) before recursive call -> Option C
  4. Quick Check:

    Check last letter before adding new letter [OK]
Hint: Check last letter to avoid consecutive repeats [OK]
Common Mistakes:
  • Filtering letters incorrectly by fixed letter
  • Checking only path length without letter comparison
  • Using includes() which disallows all repeats
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