Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Backtracking, greedy and dynamic programming

Backtracking

The backtracking technique is used to generate candidates one choice at a time.

When a choice breaks some rule, the algorithm backtracks to the previous step, dropping the candidate together with every candidate that would be built from it.

Algorithm

A backtracking solution is a recursive function that loops through the possible choices for the next step.

For each choice that does not break a rule, it calls itself with the choice added to the candidate.

backtracking_function(candidate):
    if candidate is complete:
        save it
        return
    for each choice that does not break a rule:
        backtracking_function(candidate + choice)

The algorithm itself is not complex, it is a brute force solution written with recursion.

The reason it comes as a separate topic is that it is used very often in interview problems. Those problems usually ask to generate every answer that follows a given rule.

The code is always the same template, so the main part is to find a way to drop a candidate as early as possible.

Example

Given a number n, generate every binary string of length n where no two 1s are next to each other.

Add one bit at a time. Drop a string as soon as it has two 1s next to each other, so nothing is built from it.

""
0
00
000
001
01
010
011
1
10
100
101
11
add 0
1 / 20
Binary strings
Python
def binary_strings(n: int) -> list[str]:
# Return every binary string of length n without two 1s next to each other
return []
print(binary_strings(3))
Was this lesson helpful?