Skip to the solution
MediumDSA10 min read

What is backtracking?

278 views

The problem

Question presented to candidate: "Explain what backtracking is, how it differs from plain brute force, and show me the pattern on a small problem in Python."

What a strong answer should cover:

  • The idea: build a solution one decision at a time, and undo the last decision when it cannot lead to an answer, then try the next option.
  • The three-step pattern choose / explore / un-choose, and the base case that records a complete solution.
  • Pruning: checking constraints before recursing, and why it is the difference between backtracking and brute force.
  • The state-space tree picture, and complexity as (number of nodes) ร— (work per node), usually exponential; space is the recursion depth.
  • Python details: one shared list as the path with append/pop, recording a copy (path[:] or "".join(path)), and the default recursion limit of 1000 frames that caps the depth.

Code / implementation expected: Optional โ€” a short recursive generator in Python (for example generate parentheses) that shows choose / explore / un-choose and one pruning rule.

  • backtracking

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonGenerate parentheses: brute force vs backtracking (call counts)
PythonTrace every choose, prune and undo for n = 2

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 106 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the longest increasing subsequence?

Continue