Intermediate·Concept·2 min read

Recursion and backtracking in JavaScript

Practice this question

Problems to practice

  • Fibonacci
  • Permutations
  • Subsets
  • Combination Sum
  • N-Queens
  • Sudoku

Example: permutations

JavaScript
function permute(nums) {
  const result = [];

  function backtrack(path, remaining) {
    if (remaining.length === 0) {
      result.push([...path]);
      return;
    }

    for (let i = 0; i < remaining.length; i++) {
      const val = remaining[i];
      path.push(val);
      const next = remaining.filter((_, idx) => idx !== i);
      backtrack(path, next);
      path.pop();
    }
  }

  backtrack([], nums);
  return result;
}

Interview guidance

Backtracking means trying a branch and undoing the choice when it fails.


Adapted from 16_DSA_JAVASCRIPT.md · “6. Recursion and backtracking in JavaScript”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.