neetcode.
io
Coding Interview Tips: Patterns
3 Backtracking
Patterns in
Coding
Interviews
Subsets
Typically, you will be given a list of distinct, or non-distinct integers and
asked to produce all the subsets.
Explore all subsets down one path, then backtrack by
removing the last element and explore other subsets excluding
that element.
[] [1,2,3]
[1] [2] [3]
1 2 3
[1,2] [2,3]
2 3 3 Set A is a subset to Set B if all of its
elements are found in Set B.
[1,3] Any set is a subset of itself and an empty
set is a subset of every set.
3 Order is not important in subsets.
[1,2,3]
Find more
interview tips ->
neetcode.io
Combinations
We’re given a range, [1,n] and asked to produce all possible
combinations of length k.
Similar to generating subsets, but the depth of our backtracking tree is
limited to k, ensuring that each combination contains exactly k
elements.
We explore all paths and backtrack to find other combinations
once the size of the tree becomes k.
n=4
k=2
1 2 3 4
2 3 4 3 4 4
[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]
Given an array nums of
unique integers, return all
the possible combinations.
Find more
interview tips ->
neetcode.io
Permutations
A permutation is a unique arrangement of all the numbers in nums,
where order matters and no duplicates are allowed.
For example, [1,2,3] and [1,3,2] are two distinct permutations of [1,2,3].
In this case, the answer and the base case is the leaf nodes.
1 2 3
2 3 1 3 1 2
3 2 3 1 2 1
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]
Given an array nums of
unique integers, return all the
possible permutations.
Find more
interview tips ->
neetcode.io
Join 1,000,000+
engineers preparing
for coding
interviews
neetcode.io