When to Use Recursion?

In this lesson, we will identify problems and areas where recursion should be used.

Nowadays, programming languages, including Haskell, Scala, and JavaScript, use Functional Programming which relies on recursion. Entire coding languages are now based on recursion.

An important note: recursion is not always the best method for solving a problem, even if it is possible to do so.

Let’s take a look at some tips that will help you identify whether you should use recursion or the conventional iterative method when solving a problem.

Use Where Appropriate

Recursion should be used where you feel it is appropriate or where it just feels natural. As you continue to practice recursion, this will become more obvious to you. Recursion is useful for problems that are difficult to solve when using the iterative solution.

Problem Breaks Down Into Smaller Similar Subproblems

The most obvious indication that you should use recursion is when that problem can be broken down into smaller subproblems. It is likely that a problem can be solved using recursion when you observe a pattern of that problem breaking down into similar subproblems.

Problem Requires an Arbitrary Number of Nested Loops

To solve some problems, you might have to nest an arbitrary number of loops. However, since we do not know the number of loops, the solution will get complicated. Such problems can be more easily solved using recursion.

If you know the number of loops that need to be nested, use the iterative approach. If you do not know the number of loops that need to be nested, use the recursive method.

For example, use recursion when iterating through a graph or a tree, finding all permutations of a string, etc.


In the next lesson, we will take a closer look at a recursive problem.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.