Skip to content

Software interviews

Recursion and backtracking for coding interviews, worked

Recursion solves a problem by solving a smaller copy of it. Backtracking is recursion over choices: try one, go on, and when it leads nowhere, undo it and try the next. This page gives the definitions from the NIST dictionary, the one template that covers most backtracking problems, a table showing how much early rejection saves, three patterns with worked examples and four original problems with checked answers.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What recursion and backtracking are

A recursive function does its job by calling itself on a smaller part of the job. The NIST Dictionary of Algorithms and Data Structures entry on recursion splits every recursive solution into a base case, which is answered directly, and a recursive case, which is itself three jobs: break the problem into smaller pieces, call the function on each piece and put the pieces’ answers together. Depending on the problem, any of the three can be simple or hard. Writing the base case first is the habit that prevents endless recursion.

The same dictionary’s backtracking entry fits interviews well. You make one of several choices, and when a choice turns out wrong you go back to the point where you made it and take a different one. The entry says that recursion is a handy way to remember those points and their alternatives, and that the whole process is, in concept, a depth-first search of a tree whose nodes are the choices. Depth-first search has its own lecture in the MIT OpenCourseWare course 6.006 Introduction to Algorithms, which makes it a good companion read.

Almost every backtracking solution has the same three beats, which we call choose, explore and undo. Choose an option and add it to the partial answer. Explore by recursing on the rest of the problem. Undo the choice by removing it from the partial answer, so that the next option starts from a clean state. Forgetting the undo is the most common bug, and problem 4 below shows what it costs.

How much early rejection saves

The cost of backtracking is the number of nodes in the search tree, and that depends on how early you reject. The classic example is placing n queens on an n by n board so that none attacks another. If you put one queen in each row, there are n to the power n ways to choose the columns. If you reject any column that an earlier queen attacks, before you place the next queen, the search never builds most of those boards. The counts below were produced by running the search described here, with a count of every partial board visited, including the empty board.

Queens placements: how many boards a search visits with and without early rejection, from our own count
nSolutionsBoards visited with early rejectionOne queen per row, any columns (n^n)
4217256
510543,125
6415346,656
740552823,543
8922,05716,777,216

The table is the case for pruning in one picture. At n = 8 the search that rejects early looks at about 2,000 boards, where trying every assignment would look at about 17 million. Still, backtracking is exponential in the worst case, so it suits small inputs, and it is worth saying so before an interviewer does.

The problem signals that call for backtracking

The signal is a request to list or count every arrangement that satisfies a rule, over choices made one at a time.

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
"All the ways to arrange" or "generate every"Choices made one at a timeChoose, explore, undo
"Place so that none conflict"A rule that can be tested on a partial answerReject early, before extending
"Subsets" or "combinations" with a ruleEach item is taken or notRecursion on the next item
"Repeated letters" or "no duplicate results"Equal choices give equal resultsTry each distinct option once
"Paths in a grid that do not revisit"A choice of direction, with visited cellsMark, recurse, unmark
"Count the ways" with small input sizesThe count is exponential, the input is smallBacktracking, or a formula to check it

Pattern 1: reject early

Problem 1 counts the ways to place 6 queens so that none attack another. Place one queen per row from the top. For each row, try each column, and skip any column that shares a column or a diagonal with a queen already placed. Two queens share a diagonal when the difference in their columns equals the difference in their rows. If no column works, return, and the previous row tries its next column. The point is to test the rule on the partial board, so that you never extend a board that is already wrong.

Problem 3 shows pruning in a simpler form: choose four of nine seats with no two side by side. After choosing a seat, only seats two or more places later remain allowed, so no invalid choice is ever built. Counting the completions by first seat, and checking against a closed formula, is a good way to make sure that your recursion is right.

Pattern 2: do not generate duplicates

Problem 2 counts the different strings that can be made by rearranging AABBCC. If you treat the two As as different and generate all 720 orders, you have to throw away most of them. Instead keep a count of each letter still unused, and at each position try each distinct letter with a count above zero, once. Each string is then built exactly once. The same idea handles subsets of a list with repeated values: sort first, and skip a value equal to the one you just tried at this position.

Pattern 3: mark, recurse, unmark

When the problem has a state that choices change, such as visited cells in a grid, the undo step restores it. Problem 4 counts the paths from the top left to the bottom right of a 4 by 4 grid with one blocked cell, moving in four directions and never revisiting a cell. From each cell, try each neighbor that is inside the grid, open and unvisited: mark it, recurse and unmark it on return. If you skip the unmark, cells stay marked after a path ends, and every later path is cut short. Recursion has a cost beyond time: each unfinished call holds memory, so a deep search needs a depth you can bound.

Edge cases interviewers probe

  • The base case. State it first, and check that every recursive call moves toward it.
  • An empty input. Say whether the answer is one empty arrangement or none, since the count of subsets of an empty list is 1.
  • Forgetting the undo, or undoing in the wrong place. Trace a short case and watch the partial answer after each return.
  • Duplicates in the input. Decide whether equal results count once or many times.
  • Shared mutable state. If you add the partial answer to a list of results, add a copy, since the original keeps changing.
  • Input size. Say that the search is exponential and give the size at which you would stop trusting it.

A good habit is to run your recursion by hand on the smallest case with a choice in it, writing the partial answer at each call, before you call it done.

Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from placing queens to a search on a grid.

Problem 1. In how many ways can 6 queens be placed on a 6 by 6 board so that no two queens share a row, a column or a diagonal? Give an integer.

Show the answer and the working

Answer: 4

  1. Place one queen per row, from the top row down. For each row, try each column that no earlier queen attacks, place a queen, and recurse on the next row. When no column works, return to the previous row and try its next column.
  2. Number the columns 1 to 6 and let the first row use column c. A queen in column 1 or column 6 on the first row leaves no complete placement. Each of columns 2, 3, 4 and 5 on the first row leads to exactly one complete placement.
  3. The four placements, as the column used in each row from the top, are 2 4 6 1 3 5, then 3 6 2 5 1 4, then 4 1 5 2 6 3, then 5 3 1 6 4 2.
  4. The answer is 4. The pruning matters: there are 6^6 = 46,656 ways to put one queen in each row, and testing each column against the earlier queens means the search visits only 153 partial boards, counting the empty one.

Problem 2. How many different strings can be made by rearranging all six letters of AABBCC? Two strings are the same when they read the same, even if the repeated letters were swapped. Give an integer.

Show the answer and the working

Answer: 90

  1. Build a string one position at a time, from a count of each letter still unused. At each position, try each letter whose count is above 0, once per distinct letter, then reduce its count and recurse. Trying each distinct letter once, not each copy, is what avoids duplicates.
  2. The number of leaves of this search is a multinomial count: 6! orderings if all letters were different, divided by 2 for each repeated pair, since swapping the two copies of a letter does not change the string.
  3. 6! = 720, and the three pairs divide it by 2 x 2 x 2 = 8, which gives 90.
  4. The search itself visits O(90 x 6) nodes. Treating the two As as different and then removing duplicates at the end would build 720 strings to keep 90.

Problem 3. Nine seats stand in a row. In how many ways can four seats be chosen so that no two chosen seats are next to each other? Give an integer.

Show the answer and the working

Answer: 15

  1. Choose seats left to right, and after choosing seat s, only seats from s + 2 onward remain allowed. Count the completions for each first seat.
  2. First seat 1: three more seats from seats 3 to 9, which is 7 seats, with none next to each other. That is 10 ways. First seat 2: three more from seats 4 to 9, which is 6 seats. That is 4 ways.
  3. First seat 3: three more from seats 5 to 9, which is 5 seats. That is 1 way (5, 7, 9). First seat 4: three more from seats 6 to 9, which is 4 seats, and there is no way. A later first seat has even less room.
  4. The total is 10 + 4 + 1 = 15. A closed form agrees: C(9 - 4 + 1, 4) = C(6, 4) = 15. Pruning by "start at s + 2" removes every choice that has neighbors, so no invalid choice is ever built.

Problem 4. A 4 by 4 grid of cells has its top left cell as the start and its bottom right cell as the goal. A move goes one cell up, down, left or right, onto a cell that is not blocked and has not been visited on this path. The cell in row 2 and column 2 (counting from 1 at the top left) is blocked. How many different paths lead from the start to the goal? Give an integer.

Show the answer and the working

Answer: 32

  1. Search depth first: from the current cell, try each of the four neighbors that is inside the grid, not blocked and not already on the path. Mark the cell, recurse, then unmark it when the search returns. A path counts when it reaches the goal.
  2. The grid and the blocked cell are mirror images across the main diagonal, from the top left to the bottom right. So each path that starts by moving right has a mirror path that starts by moving down.
  3. The search finds 16 paths that start by moving right. Doubling gives 32.
  4. Unmarking on the way back is the step that is easy to forget: without it, cells stay marked and later paths are missed. The count grows quickly with the size of the grid, so this approach suits small grids only.

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

A longer ladder of backtracking problems

Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 20 problem types that interviewers often use for backtracking into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.

Backtracking problem types in three sets, with a count of each
SetTypesProblems to look upWhat the set trains
Easy5listing the times a binary watch can show; letter combinations from a phone keypad; well-formed bracket strings; all orderings of distinct items; all subsets of a setThe choose, explore, undo loop on a small search space
Medium8searching a letter grid for a word; combinations that reach a sum; splitting a string into palindromes; orderings and subsets with repeated items; Gray code; restoring an address from digits; increasing subsequences; all paths through a directed graphPruning, skipping duplicates and passing state down
Hard7placing queens on a board; solving a Sudoku grid; breaking a string into words in every way; removing the fewest brackets to make a string valid; inserting operators to reach a target; partitioning into equal-sum groups; scheduling jobs to minimize the longestStrong pruning and picking the next choice with care

Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.

One habit separates solid answers from shaky ones: state the shape of the search before you code it. Say what a choice is, what the state holds, when a branch is dead and when a path is complete, then count the branches so you can give the cost. A backtracking answer that cannot name its pruning rule usually has none.

A short routine to practice

  1. Write the base case first, and what it returns.
  2. List the choices at one step and the rule that rejects a choice.
  3. Write choose, explore, undo in that order.
  4. Say how many nodes the search could visit, and what makes it smaller.
  5. Trace the smallest case by hand, writing the partial answer at every call.

Questions

What is the difference between recursion and backtracking?

Recursion is a function calling itself on a smaller part of the task. Backtracking uses recursion to try choices one at a time and returns to the point of choice to try another when a path fails.

What does every recursive solution need?

It needs a base case, where the problem is simple enough to answer directly, and a recursive case that reduces the problem and calls the function again. Without a base case the calls never stop.

How do I stop backtracking from being too slow?

Reject a partial choice as soon as it breaks a rule, before you extend it. Also make sure that you never generate the same result twice.

How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: what the base case is, what rejects a choice and what the undo restores. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms