Backtracking is an algorithmic technique that explores possible solutions step by step. When a choice leads to an invalid path, it reverses that choice and tries another possibility until a valid solution is found.
Table of Contents
Backtracking
Backtracking is a problem-solving technique where you explore different options to find a solution, and if a path leads to a dead end, you “backtrack” to a previous point and try a different path.
Backtracking is a general algorithmic technique that:
- Explores all possible decisions (choices),
- Proceeds recursively,
- Undoes previous decisions (backtracks) to explore other possibilities.
Think of it like:
- Trying all the keys on a keyring to open a lock.
- If a key doesn’t work, you go back and try the next one.
Traversing
In backtracking, when dealing with a list of items, we commonly use two ways to traverse the choices.
Way 1 : Include / Exclude — Make a binary decision
For each item, decide whether to include it or exclude it.
Level 0: []
/ \
Level 1: a - Include/Exclude a
/ \ / \
Level 2: b - b - Include/Exclude a
/ \ / \ / \ / \
Level 3: c - c - c - c - Include/Exclude a
Result abc ab ac a bc b c []
Each leaf gives one path
PythonEach leaf gives one path
Note: Important Points
- Number of decision levels = number of elements (here, level 3 and 3 elements)
- At each level, decide whether to include or exclude the current element. (ex level 2, we are deciding for element b)
- Each root-to-leaf path represents one option (subset). The path contains only the included elements along that route.
- Total leaf nodes = (2^n) because each element has two choices.
Code
def backtrack(index, path):
if index == len(nums):
print(path[:]) # print a copy of the current path
return
# include nums[index]
path.append(nums[index]) # Include
backtrack(index + 1, path) # Explore
# Exclude nums[index]
path.pop() # backtrack
backtrack(index + 1, path) # Explore
nums = ['a', 'b', 'c']
backtrack(0, [])PythonCore logic
#Include and explore
path.append(nums[index]) # include
backtrack(index + 1, path) # Explore
#Exlude and explore
path.pop() # Exclude
backtrack(index + 1, path # ExplorePythonStopping Criteria — Include/Exclude Backtracking
As discussed earlier, we get a path (subset) at each leaf, after applying the include/exclude decision to every element.
- index tracks the current level and the element being processed.
- When index == len(nums), all elements have been processed, so we have reached a leaf.
- Append a copy of the current path to result and return.
Why path[:]?
It creates a copy(shallow copy) of path because backtracking modifies the original list when exploring other branches.
In the code above, since we are just printing, both path and path[:] work fine.
But in case we are storing the path, you must use path[:]
def backtrack(index, path, result):
if index == len(nums):
result.append(path[:]) # append a copy of the current path
return
# Include nums[index]
path.append(nums[index])
backtrack(index + 1, path, result)
path.pop()
# Exclude nums[index]
backtrack(index + 1, path, result)
# Example usage
nums = ['a', 'b', 'c']
result = []
backtrack(0, [], result)
print(result)
'''
[['a', 'b', 'c'], ['a', 'b'], ['a', 'c'], ['a'], ['b', 'c'], ['b'], ['c'], []]
'''PythonThis creates a shallow copy of the list at that moment, which is safe from future mutations. It’s important when:
- You’re storing paths (e.g., in a result list).
- You want to see the snapshot of the path at the time of recursion.
Take an example use path
if index == len(nums):
result.append(path) # append a copy of the current path
return
'''
[[], [], [], [], [], [], [], []] # last value of path get reflected in all
''' PythonBecause of mutation, we got the last value, i.e [] (in our case), at all places
Bad Code
def backtrack(index, path):
if index == len(nums): # Base case: all decisions made
print(path)
return
# Choose to include nums[index]
backtrack(index + 1, path + [nums[index]])
# Choose to exclude nums[index]
backtrack(index + 1, path)
nums = ['a','b','c']
backtrack(0,[])PythonThis approach is also correct and often easier to understand, but it is not memory-efficient for larger inputs.
Both approaches have O(n) recursion-stack depth. If you store all subsets, the output itself requires O(n2n) space.
- path + [nums[index]] creates a new list.
- The original path remains unchanged.
- No path.pop() is needed.
Using path + [item]: Can incur O(n2n) total list-copying work across the recursion tree
Way 2: for loop — Explore multiple choices
You iterate through the available items and recursively explore each choice.
[]
____________________|____________________
| | |
Level 1 ['a'] ['b'] ['c']
| | |
______|____________ | |
| | | |
Level 2 ['a','b'] ['a','c'] ['b','c'] (backtrack)
| | |
Level 3 ['a','b','c'] (backtrack) (backtrack)
|
(backtrack)
PythonAt each recursive call, choose one item from the remaining candidates.
At each level, we get subsets and level = subset size (at level 2, we will get a subset of size 2)
| Level (depth) | Subset size | Subsets |
|---|---|---|
| 0 | 0 | [] |
| 1 | 1 | [a], [b], [c] |
| 2 | 2 | [a,b], [a,c], [b,c] |
| 3 | 3 | [a,b,c] |
The for loop explores the possible next items, while recursion increases the depth. Since each recursive call adds exactly one item, the depth equals the subset size in this example.
Code
def backtrack(index, path):
result.append(path[:])
for i in range(index, len(nums)):
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
result = []
nums = ['a','b','c']
backtrack(0,[])
print(result)
'''
[[], ['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['b'], ['b', 'c'], ['c']]
'''PythonWhy is no return needed?
We use i + 1 in the recursive call to ensure that each recursive step moves forward through the list. Because of this forward-only movement, the recursion naturally reaches the end of the list without needing an explicit return
Why is i+1 used?
When generating subsets, we are not interested in all possible orderings of elements (like [‘a’, ‘b’] and [‘b’, ‘a’]), because in a subset, order doesn’t matter. So [‘a’, ‘b’] and [‘b’, ‘a’] are considered the same subset.
To avoid generating duplicate permutations, we ensure that in each recursive step we only consider elements that come after the current one. That’s why we use i + 1 in the recursive call
Why two ways?
Both are important, but one is often more natural or efficient to express a particular problem.
- For-loop: Better when choosing one candidate from multiple options at each step.
- Include/Exclude: Better when making a take-or-skip decision for each item.
For- loop approach suits
- Subsets
- Combinations
- Combination Sum
- Permutations (with a different loop setup)
- (k) items from
Include/Exclude approach suits for
- Subset
- 0/1 Knapsack
- Target Sum
- Partition Equal Sum
- Subset Sum
Basics
Permutations
- All possible arrangements of the elements
- Order Matters
- Total permutations = factorial of (element)
Combinations
- All possible selections of elements
- Order doesn’t matter; example: abc, bca, cba, etc. are all the same
- Total C(n,k)= k!(n−k)!/ n, where n is the total number of elements in the set and k is the number of elements you want to choose from that set
Example: a, b, c
Permutation
[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
Combinations
1-element combinations:
[a]
[b]
[c]
2-element combinations:
[a, b]
[a, c]
[b, c]
3-element combinations:
[a, b, c]PythonTier 1 — Anchor Problems
Subset Generation (Combinations)
Using the Include/Exclude approach
def backtrack(index, path, result):
if index == len(nums):
result.append(path[:]) # append a copy of the current path
return
# Include nums[index]
path.append(nums[index])
backtrack(index + 1, path, result)
path.pop()
# Exclude nums[index]
backtrack(index + 1, path, result)
# Example usage
nums = ['a', 'b', 'c']
result = []
backtrack(0, [], result)
print(result)
'''
[['a', 'b', 'c'], ['a', 'b'], ['a', 'c'], ['a'], ['b', 'c'], ['b'], ['c'], []]
'''PythonUsing For- loop approach
def backtrack(index, path):
result.append(path[:])
for i in range(index, len(nums)):
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
result = []
nums = ['a','b','c']
backtrack(0,[])
print(result)
'''
[[], ['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['b'], ['b', 'c'], ['c']]
'''PythonCombination
A combination is essentially a subset of a specified size when choosing from distinct items.
1-element combinations:
[a]
[b]
[c]
2-element combinations:
[a, b]
[a, c]
[b, c]
3-element combinations:
[a, b, c]PythonTake k as the combination size
def backtrack(start, path):
if len(path) == k:
print(path[:])
return
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
backtrack(0, [])PythonPermutations
Using a for-loop approach
def backtrack(path, used):
if len(path) == len(nums):
print(path[:]) # copy to avoid mutation issues
for i in range(len(nums)):
if used[i]:
continue # skip already used elements
# Choose
path.append(nums[i])
used[i] = True
# Explore
backtrack(path, used)
# Backtrack
path.pop()
used[i] = False
nums = ['a', 'b', 'c']
backtrack([], [False] * len(nums))
'''
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
['c', 'b', 'a']
'''PythonIn permutations, we restart the loop from index 0 at every recursive level. Therefore, we use used[i] to ensure an element is not selected again while it is already in the current path.
With used[i], we may have combinations such as aaa, abb, etc
- used[i] = True → element is selected.
- used[i] = False → element is available again during backtracking.
Note:
- Subset: i + 1 prevents revisiting earlier indices.
- Permutation: Start from 0 each time, so used[i] prevents reusing selected elements.
Why do we restart the loop from index 0?
Because in permutations, order matters. So we need the previous item as well
- Subsets: [a, b] only; [b, a] is not generated separately.
- Permutations: [a, b] and [b, a] are both generated.
Subset vs permutation
In the subset version, we use backtrack(i + 1, path), while in permutation we don’t use i+1 logic
- Subsets: Use backtrack(i + 1, path) to avoid selecting earlier indices again and generating duplicate subsets.
- Permutations: Loop through all indices from 0 each time because any unused item can come next, including one at an earlier index. The used array prevents reusing an item.
Why do we use the for-loop approach instead of include/exclude?
The for-loop approach suits permutation questions better than Include/Exclude. In permutations, each position can contain any unused item, and the order matters.
- For loop: Naturally tries every unused item for the next position.
- Include/Exclude: Creates two branches per item, but permutations require rearranging selected items into different orders, making this approach less natural.
Tier 2 — Variation Problems
Permutations with Duplicates
def backtrack(path, used):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
# Skip duplicates: only use the *first* occurrence
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack(path, used)
path.pop()
used[i] = False
nums = [1, 1, 2]
nums.sort()
result = []
backtrack([], [False]*len(nums))
print(result) #[[1, 1, 2], [1, 2, 1], [2, 1, 1]]Pythoni > 0
This ensures we are not checking outside the array bounds when accessing nums[i – 1].
nums[i] == nums[i – 1]:
This checks if the current number is the same as the previous number. If true, we might be in a situation where a duplicate permutation could be formed.
not used[i – 1]
- This checks whether the previous identical element was already used in the current recursive path.
- If it’s not used, it means we’re still at the same recursive depth level (i.e., trying options for the same decision).
- On the other hand, if used[i – 1] is True, it means we included the previous duplicate in the current path — so it’s safe to include the current one as well, potentially forming a new unique permutation.
Without this check, your solution would generate duplicate permutations like [1,1,2] more than once.
In short: It’s a way to prevent generating duplicate permutations by ensuring we only use the first occurrence of a duplicate number in any given recursive level.
LeetCode 77: Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
def backtrack(start, path):
if len(path) == k:
result.append(path[:])
return
for i in range(start, n + 1):
path.append(i) # Choose
backtrack(i + 1, path) # Explore (i+1 → no reuse)
path.pop() # Un-choose
n = 4
k = 2
result = []
backtrack(1, [])
print(result)
'''
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
'''PythonLeetCode 90: Subsets II
Combination with duplicates
def backtrack(index, path):
result.append(path[:])
for i in range(index, len(nums)):
# Skip duplicates: only use the *first* in loop
if i > index and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
result = []
nums = ['a', 'b', 'a']
nums.sort()
backtrack(0, [])
print(result)
'''
[[], ['a'], ['a', 'a'], ['a', 'a', 'b'], ['a', 'b'], ['b']]
'''PythonLogic
- nums[i] == nums[i – 1]: we’ve already considered this number in this position, so skip to avoid duplicates.
- i > index: means this is not the first number we’re checking in this loop.
Example: a, a
We should consider the first a, and avoid the later a
Purpose of i > index
- Ensures that duplicates are only skipped within the same recursive call level.
- If we’re at a new recursive level (deeper in the tree), we want to allow the duplicate again if it’s chosen as part of a different path.
Combination Sum
Given an array of positive integers candidates (no duplicates) and a target integer target, return all unique combinations of candidates where the chosen numbers sum to target.
You may use the same number unlimited times.
def backtrack(index, path):
if sum(path) == target:
result.append(path[:])
return
if sum(path) > target:
return
for i in range(index, len(candidates)):
path.append(candidates[i]) # Choose
backtrack(i, path) # Explore (reuse allowed)
path.pop() # Un-choose
candidates = [2, 3, 6, 7]
target = 7
result = []
backtrack(0, [])
print(result)
'''
[[2, 2, 3], [7]]
'''Pythonbacktrack(i, path)
- i not i+1, because repetition of a digit is allowed
Example 7: Combination Sum II – (No Reuse, With Duplicates)
Given a collection of candidate numbers candidates (can include duplicates) and a target number target, find all unique combinations where the chosen numbers sum to the target.
Each number may only be used once.
The solution set must not contain duplicate combinations.
def explore(index,path):
if sum(path)==target:
result.append(path[:])
if sum(path)>target:
return
for i in range(index,len(nums)):
if i>index and nums[i]==nums[i-1]:
continue
path.append(nums[i])
explore(i+1,path)
path.pop()
result = []
nums = [10,1,2,7,6,1,5]
target = 8
nums.sort()
explore(0,[])
print(result)
'''
[[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
'''PythonExample 4: Permutations with Duplicates
def backtrack(path, used):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
# Skip duplicates: only use the *first* occurrence
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack(path, used)
path.pop()
used[i] = False
nums = [1, 1, 2]
nums.sort()
result = []
backtrack([], [False]*len(nums))
print(result) #[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Pythoni > 0
This ensures we are not checking outside the array bounds when accessing nums[i – 1].
nums[i] == nums[i – 1]:
This checks if the current number is the same as the previous number. If true, we might be in a situation where a duplicate permutation could be formed.
not used[i – 1]
- This checks whether the previous identical element was already used in the current recursive path.
- If it’s not used, it means we’re still in the same recursive depth level (i.e., trying options for the same decision).
- On the other hand, if used[i – 1] is True, it means we included the previous duplicate in the current path — so it’s safe to include the current one as well, potentially forming a new unique permutation.
Without this check, your solution would generate duplicate permutations like [1,1,2] more than once.
✅ In short: It’s a way to prevent generating duplicate permutations by ensuring we only use the first occurrence of a duplicate number in any given recursive level.
1 thought on “Backtracking – Exploring Possibilities Through Trial, Error & Reversal”