Forgot password? New user? Sign up

Existing user? Log in

Already have an account? Log in here.

  • Suyeon Khim
  • Silas Hundt
For recursion in computer science, see recursive functions .

Recursion formalizes the process of recognizing how solutions to smaller cases of a problem can, layer by layer, be built up to solve any case of a problem, no matter how enormous. Needless to say, it can be tricky to figure out how to solve infinitely many problems simultaneously. That's what this wiki page will explain, so brace yourself for some problem solving that feels a bit loopy and oddly cyclic at times.

When to Use Recursion

Recursive problem solving, patterns with a longer memory, infinite recursion, further topics in recursion, unsolved recursion-related combinatorics problems.

Some signs that recursion might be a good method for attacking a problem are as follows:

The problem asks for the value of a large case, and you can determine small values or they are given. There is a clear connection between small cases and large cases.

This example problem can be solved straight, without recursion. But the recursive solution is a beautiful and efficient approach.

How many red triangle tiles will be needed for the next \((\)the \(4^\text{th})\) layer of this star pattern? There's no shame in solving this puzzle by counting (although doing so accurately might be trickier than you think). You might even come up with a clever way to count – say, by recognizing that each arm of the star will need the same number of triangles. But neither of these methods is as practical or as elegant as recursion.

If you're not convinced yet that a recursive method is worth the investment, consider counting all of the triangles in the \(1000^\text{th}\) level of this pattern. There are 23988 of them.

Why use recursion? Because no one would ever want to count that high! Using recursion, you'll be able to solve this problem easily by the end of the next section.

Recursion should be applied as a technique when the problem you're solving is like an onion. Using recursion requires realizing that a big, complex problem that's likely to make you cry is really just a slightly smaller problem, plus one super-thin layer. And that problem, in turn, is just a slightly smaller problem, plus one super-thin layer...

Steps of Recursive Problem Solving Create and analyze smaller cases of the problem. Try to construct larger cases using smaller cases. Make a conjecture (a guess) about how small cases are generally related to larger cases. Prove your conjecture and translate it into a general formula that uses the answers to smaller/simpler cases of the problem to find the answer to a larger/more difficult case. Use the formula from step 4 to build up to the solution to the specific layer you care about.

Critically, in step 4, the relationship between smaller and larger cases needs to be a general one for constructing any case of the problem from earlier/smaller cases, not just a single example of making a specific complex case from specific earlier cases.

These steps are the secret to efficiently and beautifully solving many problems that would make the average Joe weep.

How many red triangle tiles will be needed for the next (the 4th) layer of this star pattern? We will solve this problem using recursion. Thinking recursively solves this problem beautifully and efficiently. Step 1 Create and analyze smaller cases of the problem. The natural cases in this problem are the sequential layers of the star: The first layer has 12 triangles. The second layer has 36 triangles. The third layer has 60 triangles. Step 2 Try to construct larger cases using smaller cases. Compare the \(1^\text{st}\) layer to the \(2^\text{nd}\) layer, and the \(2^\text{nd}\) layer to the \(3^\text{rd}\) layer: Step 3 Make a conjecture (a guess) about how small cases are generally related to larger cases. Notice that by moving groups of the triangles in one layer away from the center and then adding 24 extra triangles in diamond-shaped pairs, we can make the next layer of the pattern from each previous layer. This geometric relationship between two sequential layers is a general one that works for any two sequential layers. Step 4 Prove your conjecture and translate it into a general formula that uses the answers to smaller/simpler cases of the problem to find the answer to a larger/more difficult case. Each layer will require 24 more triangles than the layer just before it! If \(C_n\) is the answer to case \(n\) of the problem, then \(C_n = C_{n-1} + 24\) and \(C_1\) = 12 since with one layer, there are 12 triangles in the star. Step 5 Use the formula from step 4 to build up to the solution to the specific layer you care about. Finding the number of triangles in the \(4^\text{th}\) layer: Case 1: There are 12 triangles in the initial star. Case 2: There are \(12 + 24 = 36\) triangles in the \(2^\text{nd}\) layer. Case 3: There are \(36 + 24 = 60\) triangles in the \(3^\text{rd}\) layer. Case 4: There are \(60 + 24 = \boxed{84}\) triangles in the \(4^\text{th}\) layer. \(_\square\)

How many white triangles would you need to make the \(5^\text{th}\) layer of this tile pattern?

Too big for counting? Definitely. Too big for recursion? Never!

How many white triangles would be needed to make the \(1001^\text{st}\) layer of this tiling pattern?

Finding a recurrence relation requires identifying some regular relationship between each case of a problem and the earlier cases. But many times it won't be solely the case just before that's relevant. Sometimes, later cases will evolve from combining two, three, or any number of previous cases together.

You're creating a catalog of tile designs for a friend. In this series of designs, the area to be tiled is 2'' x 16'' and the tiles are each 1'' x 2''. How many different ways are there to cover the area with tiles? A few examples:

Step 1 Create and analyze smaller cases of the problem.

The length of the area can be decreased in order to make this problem simpler. It is definitely easier to count how many ways a 2'' x 5'' rectangle could be tiled for example. Additionally, our wishful thinking at this stage is that somehow the solution to the 2'' x 16'' case would be easy to figure out if only we knew the solution to the 2'' x 15'' case already... The sequence of problems this reasoning suggests is to consider tiling a 2'' x 1'' area, then a 2'' x 2'' area, then a 2'' x 3'' area, etc. Therefore, the general case is 2'' x n''. Solving the Smallest Cases \(C_1=1\) There is 1 way to tile a 1'' x 2'' area. \(C_2=2\) There are 2 ways to tile a 2'' x 2'' area. \(C_3=3\) There are 3 ways to tile a 3'' x 2'' area. \(C_4=5\) There are 5 ways to tile a 4'' x 2'' area.

Step 2 Try to construct larger cases using smaller cases.

We could keep doing out cases one at a time or, at any point, we can start looking for a pattern. Try using the sets above as a tool to identify all of the tiling patterns for \(C_5\). How can you make a larger tile pattern out of a smaller one?

Step 3 Make a conjecture (a guess) about how small cases are generally related to larger cases.

Say, for example, that we're trying to figure out the number of tiling patterns for \(n = 5\), aka, the number of ways to tile a 5'' x 2'' area with dominoes. To start, we know that there are at least 5 ways to do it: take each of the five \(n = 4\) solutions and add one new vertical tile on the left: But are there more solutions? Yes. Above are all of the solutions that start with one vertical tile, but what about all of the solutions that start with two horizontal tiles on the far left? If there are 3 inches left to fill after these two tiles on the left, how many ways are there to fill these 3 inches? \(C_3 = 3.\)

Step 4 Prove your conjecture and translate it into a general formula that uses the answers to smaller/simpler cases of the problem to find the answer to a larger/more difficult case.

Generalizing this observation, for any \(n\)'' x 2'' area, there are \(C_{n-1}\) tilings with one vertical domino on the far left, and \(C_{n-2}\) tilings with two horizontal dominoes on the far left. So \(C_n = C_{n-1} + C_{n-2}\). In words, the solution to each case is the sum of the solution to the two previous cases. That's the Fibonacci sequence ! Apart for the base case terms which are, in this case, \(C_1 = 1\) and \(C_2 = 2\).

Step 5 Use the formula from step 4 to build up to the solution to the specific layer you care about.

Using 1'' x 2'' dominoes, there's one way to tile a 1'' x 2'' area, 2 ways to tile a 2'' x 2'' area, 3 ways to tile a 3'' x 2'' area, and 5 ways to tile a 4'' x 2'' area.

How many ways are there to tile a 5'' x 2'' area?

You're creating a catalog of tile designs for a friend. In this series of designs, the area to be tiled is 2'' x 16'' and the tiles are each 1'' x 2''.

How many different ways are there to cover the area with tiles?

Note: The image shows a few examples that describe such scenario.

At this point, stopping at any specific point in the recursion process might feel kind of arbitrary--why get off at the \(1001^\text{st}\) floor of a building when you can take the elevator up to the moon... and beyond?

Whenever you define a recursive process, you can imagine taking the infinite limit of that process, asking, "What are we approaching as we repeat the process over and over and over again?" Sometimes, infinity does amazing things to recursion.

Fractals are a beautiful application of the infinite extension of recurrence relations. One particular kind of fractal called an iterated function system (IFS) is pretty much just visual recursion on an infinite kick. These fractals are made using recursive processes. Here are a few examples of IFS fractals:

Sierpinski's Triangle 1) Start with a right isosceles triangle of side length 1. 2) Draw lines connecting the centers of each edge and remove the inverted triangle that these edges form. 3) Draw lines connecting the centers of each edge of the remaining solid triangles. Remove the inverted triangles that these edges form. ... repeat step 3 process over and over again, each time removing smaller, inverted triangles from the center of each remaining triangle.
Infinitely many. For example, imagine the left corner of the triangle at the origin of a graph and the left edge of the triangle as a vertical line from 0 to 1. In the first iteration of the process, the center point \(\frac12\) is removed, then \(\frac14\) and \(\frac34,\) then \(\frac18, \frac38, \frac58,\) and \(\frac78,...\) etc. But \(\frac13\) will never be removed, nor will \(\frac19, \frac1{27},...\) etc. In fact, on the vertical edge of the figure, even though infinitely many points are removed, more points remain in the fractal.
There will be no line segments left in the image. The vertical left edge of the final fractal looks like a line, but so many points have been removed from it that there are no continuous sections of line left. In other words, eventually, every line segment in the image has at least one point removed from it, breaking it. So the final 'length' of every segment will be 0.
None. For any patch of solid area that initially exists, eventually, some portion of it is removed by the recursive process. Therefore, no solid patches of area remain after executing the recursive process infinitely many times.

Conclusion: Fractals are weird !

  • Linear Recurrence Relations
  • Finding Irregular Closed Form Solutions via the Substitution Method (Converting a recursive pattern into a formula that immediately gives out an answer for any specific case, without needing to sequentially figure out every smaller solution.)
  • Finding the Closed Form of Recurrence Relations via the Master Theorem
  • Even More about Recurrence Relations
  • Generating Functions - Solving Recurrence Relations
  • The Y-Combinator (Lambda Calculus)
Main article: Unsolved Problems in Combinatorics
  • TODO: Example 1
  • TODO: Example 2

Problem Loading...

Note Loading...

Set Loading...

How-To Geek

What is recursion in programming, and how do you use it.

Recursion is an important part of functional programming that can help solve complex problems with elegant solutions.

Quick Links

What is recursion, the dangers of recursion, use recursion sparingly.

Recursion is an important part of functional programming that can help solve complex problems with elegant solutions. However, it's important to understand the pros and cons so that it can be done correctly.

The short answer is that Recursion is basically whenever a function calls itself, usually with a different input passed to the child function. It calls itself over and over until an exit condition is reached, and then passes the results back up the call stack, potentially modifying them on the way up as well.

how to solve recursion problems

The long answer is that recursion can help solve complicated problems by breaking them down into smaller subsets of the main problem. Often, you will have data structures containing nested data. Breaking this down into smaller amounts of data will make this easier to process.

how to solve recursion problems

For example, say each leaf in the tree had a value associated with it, and we wanted to find the sum of all the values. We could do that with a function like the following, which traverses the tree leaf by leaf, inspecting all the children and calculating the total.

int CountAllLeaves(Leaf currentLeaf)

// Start with the current value

int Total = currentLeaf.value;

// Add any children to the value, if any

foreach(Leaf childLeaf in currentLeaf.children)

Total = Total + CountAllLeaves(childLeaf);

return Total;

This works because CountAllLeaves doesn't care about which Leaf you call it with. It repeatedly calls itself until it hits the final leaf in the tree, which doesn't have any children. Because of that, it simply returns its own value. That value is passed to the parent leaf, which adds the child's value to its own, and then repeats for all the siblings that child leaf has. In the end, the final result of the function will be the total sum of all the leaves in the tree.

At some point, you must reach the halting case, which is the piece of the problem that you know the answer to without making any more recursive calls. Otherwise, the function would loop forever, causing the program to crash. In this case, the halting case is when the function reaches a leaf that doesn't have any children.

It doesn't have to be about nested data structures like trees. You can write recursive functions around any type of problem. For example, calculating the factorial of a number involves multiplying it by each number smaller than it. You can do this very easily with recursion:

int Factorial(int n)

if (n <= 1)

return n * Factorial(n-1);

In this example, the halting case is when

 reaches 1, where it finally returns a value and the call stack can be collapsed.

Lets look at a real-world example. In this bit of code, there is a

 class which contains multiple UI elements attached to it, as well as multiple child containers with their own elements. It must be "rendered" out to a flat list of elements which can be shown on screen.

This is basically another tree data structure, so the approach is similar. Except, in this case, the total variable is a list, which gets the Elements lists of each Container appended to it.

how to solve recursion problems

The magic of doing it using recursion is that it preserves the Z-order of the elements. Elements drawn after other elements go on top, so the youngest child container will always display on top. In this scenario, I also found it useful to display overlay elements, which get added after the other elements and children finish rendering.

So, when should you use recursion in your code? The answer is you should actually probably avoid it in most situations, especially when an iterative solution using a simple loop will get the job done.

Every time you call a function, your program allocates resources towards that function. All local variables and info go onto the stack, which is a Last-In, First-Out (LIFO) data structure. This means the latest function call is always the first to be removed, like a bucket where you always remove the top element.

how to solve recursion problems

The problem with recursion is that it can use a nested function call for each element being processed. This results in a lot more overhead, as each function call needs its own set of local variables and parameters. It will take extra processing time compared to a loop based approach.

Loops don't have this problem. After each loop iteration, the stack will have the top element cleared off. It could process a billion elements using the same stack.

If you use too many resources with recursive function calls, it can result in stack overflow, where the program can crash just based on too many nested calls. This can happen with particularly large data sets, or with poor algorithms like binary or exponential recursion, which call themselves multiple times per function call.

Recursion is a nice thing to have for certain problems, but there are basically no recursive solutions to problems that can't also be solved using loops (except for nested recursion like Ackerman's function ). Even complicated tree data structures can be traversed using loops and stacks . If you need to handle large amounts of data, or care a lot about performance, you might be better off using an iterative solution.

The other problem with recursion is that it can lead to code that is difficult for other people to understand, as it usually takes a bit of head scratching before someone gets it. While it often seems like the more "elegant" solution, your job as a programmer is not to show off, and is instead to write functional, readable code.

In any case, you'll want to think about whether or not the problem at hand would be better off using a loop. Recursion should be your last resort for problems that would be much more complicated without it. In fact, in my entire 40,000 lines of source code, I only had one example of recursion for this article.

And, after a second glance at it, I actually noticed a problem. While it worked fine, it was written the lazy, obvious way, and as such is using a lot more memory than it needs. This isn't really a problem with the small data structures it's handling, but it was creating a

 for each call of the function, and adding the results of the children below it. This meant that if it was given a container with deeply nested children, it would be storing the same data over and over for no reason.

The solution in this case was to pass the recursive function a reference to an external list, and add all the elements to it directly. This also involved changing the

 function into a function that handled the top-level setup for the recursive build function.

how to solve recursion problems

This accomplishes exactly the same solution of adding each element in the proper order, but fixes the problem of memory usage going up exponentially with each call.

Still, I'm happy with this function as it's quite concise and gets the job done easily. If I was to convert this to a solution using a loop, it would be a lot more complicated and do the exact same thing. You will need to weigh the pros and cons of using a recursive solution, and only use them where you're not expecting serious resource usage. In this case, I'm not expecting to be calling this function with nested containers that are hundreds of elements deep, so using recursion here is fine.

For more info on this topic, see our guide to Recursion .

  • 90% Refund @Courses
  • Data Structure
  • Analysis of Algorithms
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms

Related Articles

  • Solve Coding Problems
  • Introduction to Recursion - Data Structure and Algorithm Tutorials
  • What is Recursion?
  • Difference between Recursion and Iteration
  • Types of Recursions
  • Finite and Infinite Recursion with examples
  • What is Tail Recursion
  • What is Implicit recursion?
  • Why is Tail Recursion optimization faster than normal Recursion?
  • Recursive Functions
  • Difference Between Recursion and Induction

Recursion in different languages

  • Recursion in Python
  • Recursion in Java
  • Recursion in C#
  • How to Understand Recursion in JavaScript ?

Standard Problems on Recursion

  • Program for Tower of Hanoi Algorithm
  • Time Complexity Analysis | Tower Of Hanoi (Recursion)
  • Find the value of a number raised to its reverse
  • Recursively remove all adjacent duplicates
  • Print 1 to n without using loops
  • Print N to 1 without loop
  • Sort the Queue using Recursion
  • Reversing a queue using recursion
  • Mean of array using recursion
  • Binary to Gray code using recursion
  • Sum of natural numbers using recursion
  • Delete a linked list using recursion
  • Product of 2 Numbers using Recursion
  • Decimal to binary number using recursion
  • Sum of array elements using recursion
  • How to Sort a Stack using Recursion
  • Reverse a Doubly linked list using recursion
  • Programs for Printing Pyramid Patterns using Recursion
  • DFS traversal of a Tree
  • Length of longest palindromic sub-string : Recursion
  • Count Set-bits of number using Recursion
  • Print reverse of a string using recursion
  • Print Fibonacci Series in reverse order using Recursion
  • Java Program to Reverse a Sentence Using Recursion
  • Program for length of a string using recursion
  • Sum of digit of a number using recursion
  • Program to calculate value of nCr using Recursion
  • Find geometric sum of the series using recursion
  • Bottom View of a Binary Tree using Recursion
  • Convert a String to an Integer using Recursion
  • Tail recursion to calculate sum of array elements.

Practice Sets on Recursion

  • Recursive Practice Problems with Solutions
  • Practice Questions for Recursion | Set 1
  • Practice Questions for Recursion | Set 2
  • Practice Questions for Recursion | Set 3
  • Practice Questions for Recursion | Set 4
  • Practice Questions for Recursion | Set 5
  • Practice Questions for Recursion | Set 6
  • Practice Questions for Recursion | Set 7
  • Practice questions for Linked List and Recursion

Introduction to Recursion – Data Structure and Algorithm Tutorials

What is Recursion?   The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH) , Inorder/Preorder/Postorder Tree Traversals , DFS of Graph , etc. A recursive function solves a particular problem by calling a copy of itself and solving smaller subproblems of the original problems. Many more recursive calls can be generated as and when required. It is essential to know that we should provide a certain case in order to terminate this recursion process. So we can say that every time the function calls itself with a simpler version of the original problem.

Need of Recursion

Recursion is an amazing technique with the help of which we can reduce the length of our code and make it easier to read and write. It has certain advantages over the iteration technique which will be discussed later. A task that can be defined with its similar subtask, recursion is one of the best solutions for it. For example; The Factorial of a number.

Properties of Recursion:

  • Performing the same operations multiple times with different inputs.
  • In every step, we try smaller inputs to make the problem smaller.
  • Base condition is needed to stop the recursion otherwise infinite loop will occur.

Algorithm: Steps

A Mathematical Interpretation

Let us consider a problem that a programmer has to determine the sum of first n natural numbers, there are several ways of doing that but the simplest approach is simply to add the numbers starting from 1 to n. So the function simply looks like this,

approach(1) – Simply adding one by one f(n) = 1 + 2 + 3 +……..+ n

but there is another mathematical approach of representing this,

approach(2) – Recursive adding  f(n) = 1                  n=1 f(n) = n + f(n-1)    n>1

There is a simple difference between the approach (1) and approach(2) and that is in approach(2) the function “ f( ) ” itself is being called inside the function, so this phenomenon is named recursion, and the function containing recursion is called recursive function, at the end, this is a great tool in the hand of the programmers to code some problems in a lot easier and efficient way.

How are recursive functions stored in memory?

Recursion uses more memory, because the recursive function adds to the stack with each recursive call, and keeps the values there until the call is finished. The recursive function uses LIFO (LAST IN FIRST OUT) Structure just like the stack data structure. https://www.geeksforgeeks.org/stack-data-structure/  

What is the base condition in recursion?   In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems.   

In the above example, the base case for n < = 1 is defined and the larger value of a number can be solved by converting to a smaller one till the base case is reached.

How a particular problem is solved using recursion?   The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For example, we compute factorial n if we know the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0. 

Why Stack Overflow error occurs in recursion?   If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this.

If fact(10) is called, it will call fact(9), fact(8), fact(7), and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error. 

What is the difference between direct and indirect recursion?   A function fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. The difference between direct and indirect recursion has been illustrated in Table 1. 

What is the difference between tailed and non-tailed recursion?   A recursive function is tail recursive when a recursive call is the last thing executed by the function. Please refer tail recursion article for details. 

How memory is allocated to different function calls in recursion?   When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues. Let us take the example of how recursion works by taking a simple function. 

Time Complexity: O(1) Auxiliary Space: O(1)

When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4 are pushed into the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0) . printFun(0) goes to if statement and it return to printFun(1) . The remaining statements of printFun(1) are executed and it returns to printFun(2) and so on. In the output, values from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has been shown in below diagram.

recursion

Recursion VS Iteration

Now, let’s discuss a few practical problems which can be solved by using recursion and understand its basic working. For basic understanding please read the following articles.  Basic understanding of Recursion. Problem 1: Write a program and recurrence relation to find the Fibonacci series of n where n>2 .  Mathematical Equation:   

Recurrence Relation:  

Recursive program:  

Implementation:  

Time Complexity: O(2 n ) Auxiliary Space: O(n)

Here is the recursive tree for input 5 which shows a clear picture of how a big problem can be solved into smaller ones.  fib(n) is a Fibonacci function. The time complexity of the given program can depend on the function call. 

fib(n) -> level CBT (UB) -> 2^n-1 nodes -> 2^n function call -> 2^n*O(1) -> T(n) = O(2^n)  

For Best Case. 

Working:  

how to solve recursion problems

Problem 2: Write a program and recurrence relation to find the Factorial of n where n>2 .  Mathematical Equation:  

Recursive Program:   Input: n = 5  Output:   factorial of 5 is: 120 Implementation:  

Time complexity: O(n) Auxiliary Space: O(n)

Working:    

how to solve recursion problems

Diagram of factorial Recursion function for user input 5.

Example:  Real Applications of Recursion in real problems

Recursion is a powerful technique that has many applications in computer science and programming. Here are some of the common applications of recursion:

  • Tree and graph traversal : Recursion is frequently used for traversing and searching data structures such as trees and graphs. Recursive algorithms can be used to explore all the nodes or vertices of a tree or graph in a systematic way.
  • Sorting algorithms : Recursive algorithms are also used in sorting algorithms such as quicksort and merge sort. These algorithms use recursion to divide the data into smaller subarrays or sublists, sort them, and then merge them back together.
  • Divide-and-conquer algorithms : Many algorithms that use a divide-and-conquer approach, such as the binary search algorithm, use recursion to break down the problem into smaller subproblems.
  • Fractal generation : Fractal shapes and patterns can be generated using recursive algorithms. For example, the Mandelbrot set is generated by repeatedly applying a recursive formula to complex numbers.
  • Backtracking algorithms : Backtracking algorithms are used to solve problems that involve making a sequence of decisions, where each decision depends on the previous ones. These algorithms can be implemented using recursion to explore all possible paths and backtrack when a solution is not found.
  • Memoization : Memoization is a technique that involves storing the results of expensive function calls and returning the cached result when the same inputs occur again. Memoization can be implemented using recursive functions to compute and cache the results of subproblems.

These are just a few examples of the many applications of recursion in computer science and programming. Recursion is a versatile and powerful tool that can be used to solve many different types of problems.

Explanation: one real example of recursion:

Recursion is a programming technique that involves a function calling itself. It can be a powerful tool for solving complex problems, but it also requires careful implementation to avoid infinite loops and stack overflows. 

Here’s an example of implementing recursion in Python:

In this example, we define a function called factorial that takes an integer n as input. The function uses recursion to compute the factorial of n (i.e., the product of all positive integers up to n).

The factorial function first checks if n is 0 or 1, which are the base cases. If n is 0 or 1, the function returns 1, since 0! and 1! are both 1.

If n is greater than 1, the function enters the recursive case. It calls itself with n-1 as the argument and multiplies the result by n. This computes n! by recursively computing (n-1)!.

It’s important to note that recursion can be inefficient and lead to stack overflows if not used carefully. Each function call adds a new frame to the call stack, which can cause the stack to grow too large if the recursion is too deep. In addition, recursion can make the code more difficult to understand and debug, since it requires thinking about multiple levels of function calls.

However, recursion can also be a powerful tool for solving complex problems, particularly those that involve breaking a problem down into smaller subproblems. When used correctly, recursion can make the code more elegant and easier to read.

What are the disadvantages of recursive programming over iterative programming?   Note that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true. The recursive program has greater space requirements than the iterative program as all functions will remain in the stack until the base case is reached. It also has greater time requirements because of function calls and returns overhead.

Moreover, due to the smaller length of code, the codes are difficult to understand and hence extra care has to be practiced while writing the code. The computer may run out of memory if the recursive calls are not properly checked.

What are the advantages of recursive programming over iterative programming?   Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree traversals, Tower of Hanoi , etc. For such problems, it is preferred to write recursive code. We can write such codes also iteratively with the help of a stack data structure. For example refer Inorder Tree Traversal without Recursion , Iterative Tower of Hanoi .

Summary of Recursion:

  • There are two types of cases in recursion i.e. recursive case and a base case.
  • The base case is used to terminate the recursive function when the case turns out to be true.
  • Each recursive call makes a new copy of that method in the stack memory.
  • Infinite recursion may lead to running out of stack memory.
  • Examples of Recursive algorithms: Merge Sort, Quick Sort, Tower of Hanoi, Fibonacci Series, Factorial Problem, etc.

Output based practice problems for beginners:   Practice Questions for Recursion | Set 1   Practice Questions for Recursion | Set 2   Practice Questions for Recursion | Set 3   Practice Questions for Recursion | Set 4   Practice Questions for Recursion | Set 5   Practice Questions for Recursion | Set 6   Practice Questions for Recursion | Set 7 Quiz on Recursion   Coding Practice on Recursion:   All Articles on Recursion   Recursive Practice Problems with Solutions

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule. Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

  • DSA in Java
  • DSA in Python
  • DSA in JavaScript

Please Login to comment...

  • DSA Tutorials
  • tail-recursion
  • Anshul_Aggarwal
  • Ashish_rana
  • Kirti_Mangal
  • divyeshrabadiya07
  • akashkumarsen4
  • avanitrachhadiya2155
  • divyesh072019
  • iamartyayadav
  • chinmoy1997pal
  • sumitgumber28
  • abhishek0719kadiyan
  • saurabhkuntal34
  • saragupta0302
  • shreyasnaphad
  • yashagarwal2852002
  • shivamgupta310570
  • anikettchavan
  • chandanagarwv9m5

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • All Articles
  • Let's Connect
  • Fundamentals
  • Soft Skills
  • Side Projects

A Guide To Recursion With Examples

You are at your desk at WeSellEverythingAndAnythingMegacorp, the fantastic e-commerce you work for. You’re trying to write some code while thinking intensively about your lunch. Suddenly, a voice break your incredible concentration. It’s Davina, your colleague developer, hired only a few moons ago. She has a problem and she thinks you can help her.

She needs to display a directory tree, and she believes that she needs to use recursion. But she never quite understood the concept.

Recursion. The word alone brings back some painful and confused memory. You didn’t do much recursion the last ten years of glorious copy past from Stack Overflow. Where to begin? What example to give?

You begin to search the deep Internet, and you stumble upon this article. Welcome, dear reader! It’s now my task to help you.

If you’re used to implement iterations all over the place, using for , while , foreach , for in , or similar constructs, the concept of recursion can be difficult to grasp. It’s another way to think about a problem and its solution, and, only for that, it’s great. Widening our skills for problem solving is always useful, arguably more than learning the last trendy framework.

While iteration can solve everything you want, a whole range of problems are way, way easier to solve using recursion. To grasp the good mindset for understanding and applying recursive solutions, we’ll see in this article:

  • What’s recursion.
  • How to recursively calculate a sum.
  • How to recursively change words in a sentence.
  • How to display a tree of directory with an unknown depth using recursion.

This article include some exercises. You and Davina will be granted Great Invoker of the Recursive Demon Unleashed if you try to solve each of them! Here are the rules: spend from 20 minutes to an hour for each exercise. No more, no less. In general, put some good will in them, but avoid anger and deep sadness.

When you feel you’re blocked, you can as well do a break and come back to it later. This is very often the best thing to do.

Now that you know the rules, let’s go hunting the Ghost of Recursion all together!

What Is Recursion?

Before diving into examples, we shall first understand what recursion is. Let’s define it, thanks to the computer science wiki :

A method where the solution to a problem depends on solutions to smaller instances of the same problem.

Decomposing a problem is a very useful technique to solve it without headaches. I spoke already about it when I revisited the Single Responsibility Principle .

In short, decomposing a problem means:

  • Breaking down a problem into smaller and simpler sub-problems.
  • Solving the sub-problems to solve the main problem.

If these sub-problems are all smaller instances of the same problem , it means that a solution to a sub-problem is valid for every other sub-problems. You need to apply the same solution to every single one of them, again and again.

When you reach the smallest sub-problem, your main problem will be solved, too. How cool is that?

How To Do Recursion?

To apply a recursive solution to a problem, you need to go through two steps:

  • Finding the base case .
  • Finding the recursive steps .

The Base Case

Recursion can be seen as a reduction from the bigger problem to the simplest, smallest instance of the same problem. The smallest of all sub-problems is called the base case . This is what we should find first.

In the real world, your recursive process will often take the shape of a function. Like any function, it will take some input and give back some output. The base case is the simplest process the function can do for a given input.

The Recursive Step

When you’ve found the base case, you’ve solved the smallest sub-problem, but you still have to solve every other ones.

The recursive step is the reduction we spoke about earlier: applying the same solution to every sub-problem. You’ll reduce the main problem into a chain of smaller sub-problems, until your problem is so simple it reaches the base case.

Recursion In Action

Davina looks at you, desperate, horribly lost. You begin to question as well where I’m heading to while reading this article. You’re right: enough theory! It’s now practice time.

I would advise you to try to solve the problems given in this article. You’ll then understand my theoretical babbling from earlier, and, as a result, how to apply recursion to a wide range of problems. You’ll remember it, too, because you tried it with your own brain.

These exercises are in PHP. If you know already a language with a C-like syntax, it shouldn’t be too hard for you to follow. You can as well try to translate the examples in another language. They are pretty short, so it shouldn’t take weeks.

If you don’t understand anything about PHP, you can still ask me to do them in another language. I would be happy to do it depending on the need.

Sum of Range

Let’s take a simple problem for the beginning: calculating the sum for a range of positive integers, starting from 0.

For example:

  • Sum range to 5: 0 + 1 + 2 + 3 + 4 + 5 = 15
  • Sum range to 10: 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
  • Sum range to n: 0 + 1 + 2 + 3 + 4 + 5 + ... + n = ???

Your challenge, if you accept it, is to write a function which has these properties:

  • The variable n is the argument of the function.
  • The output have to be the sum of the range from 0 to n .

Iterative Solution

Before using recursion, let’s try to solve the problem using the good old iterative for loop. Davina is already solving it, so fire your best editor and let’s go!

This can be seen as an accumulation : we first go from 0, and then we add the good numbers to $total .

Recursive Solution

To solve the problem using recursion, we need to go through the two steps we saw above.

The base case is the smallest possible sub-problem. What would be the value of n which would make our function trivial?

If n is 0, the sum of range from 0 to 0 is… 0. This is the smallest sub-problem of our main problem. With this base case, we can already write the beginning of our function:

The Recursive Steps

As we said, recursion can be seen as a reduction . We’ll take n and we’ll reduce it till we reach our base case, when n equals 0.

Our main problem is now: to sum a range of positive integers from n to 0. If n is equal to 5, it will be: 5 + 4 + 3 + 2 + 1 + 0 = 15 .

How to decompose this problem to smallest instance of the same problem? A smaller sub-problem would be adding one number at a time instead of adding 5 different numbers.

We begin with n == 5 . The first sub-problem would be adding a number. The solution is adding 4, which is (n - 1) . Now, n == 4 , and we can continue to apply this solution: adding (n - 1) , which is 3 . We apply this solution again and again, till we reach our base case, n == 0 . That’s all. We’re done.

Now, you should be able to try to complete our recursiveSumRange function we began earlier.

Calling sumRange again and again allows us to decrease n by 1 at each step, as we wanted.

Most of the time, people explain recursion by calling the same function repeatedly. Even if it’s partially true, we shouldn’t think about it that way.

What happens here is much more than repeating the call of a function . It’s more useful to think of it as a chain of deferred operations .

Let’s zoom on each return statement for each step of the recursive process:

  • return 5 + sumRange(4)
  • return 5 + 4 + sumRange(3)
  • return 5 + 4 + 3 + sumRange(2)
  • return 5 + 4 + 3 + 2 + sumRange(1)
  • return 5 + 4 + 3 + 2 + 1 + sumRange(0)
  • return 5 + 4 + 3 + 2 + 1 + 0

From the first step to the 5th, you can see an expansion . Every sum operation we need are chained. However, nothing is added at that point: that’s why we speak of deferred operations . They will be executed later.

At the 5th call of the sumRange function, we gives 0 as argument. It’s our base case! That’s why only 0 is returned from sumRange at the 6th step. It’s where the reduction happens. The function sumRange doesn’t call itself anymore so every summation operation can be executed.

These deferred operations are not visible in your code or in your output: they are in memory. The program needs to held them somehow, to be able to execute them at the end.

If we would had not specified the base case, the recursive process would never end. For example:

What happens in that case?

  • return 5 + 4 + 3 + 2 + 1 + 0 + sumRange(-1)
  • return 5 + 4 + 3 + 2 + 1 + 0 + (-1) + sumRange(-2)
  • return 5 + 4 + 3 + ... + sumRange(-488117)
  • return 5 + 4 + 3 + ... + sumRange(-488118)

At that point, everything crash and I get a wonderful error message telling me that I blew up the memory allocation limit. As I was saying above, every deferred operation were held in memory, until there weren’t enough memory to contain them all!

Changing Words In a Sentence

Davina seems now full of hope to understand what recursion is. She never really thought about it that way. That’s great! Let’s continue our recursive exploration.

I’m sure you always wanted to change words in a sentence recursively. Personally, it’s my biggest dream.

The goal is to design a function which takes a string as argument, and recursively change some words. The words “i” and “me” will become “you”, the word “you” will become “i”.

We’ll only deal with lowercase sentences to make things easier.

For example, if you give the sentence i do not know if you hear me as argument of your recursive function, the output must be you do not know if i hear you .

To help you out, here are some helper functions you can use:

You remind to Davina to find the best case first, and then the recursive steps.

If you have difficulties to find the recursive solution, you can try to solve the problem with an iterative loop first. I have faith in you. You can make it!

Here’s the recursive solution:

This example is similar to the previous one. This time, we don’t have deferred summations, but deferred concatenations, while changing the words as we go.

First, we had to find the base case. What’s the value of $sentence which makes everything trivially simple? An empty sentence, which return an empty sentence. We write:

Second, we need the recursive steps. Since the sentence can be of any length, it’s easier to consider one word at a time. Then, we can change it if we need to, before looking at the next word. If there is no word to change anymore, we reach our base case (the empty sentence).

That’s all! Who said that recursion was difficult?

Displaying a Directory Tree

At that point, Davina ask you this legitimate question: “What’s the point to know how to create recursive functions if we can use good old iterative loops instead? Can we use loops for my problem?”.

You look at Davina’s problem. You answer is clear: no, iteration would not be a good solution for that.

Davina is developing a backoffice for the content department of the e-commerce you’re working for. Copywriters want to be able to choose images of product from any sub-directory of a file system.

She needs to display a tree of directories which can have any depth , that is, an unknown number of nested sub-directories.

Thinking about the problem with Davina, you come up with a simple solution: having each directory and sub-directories as keys of a hashmap. You could then iterate through it and display each directory.

To make the problem more concrete and easier to reason about, you decide to create an arbitrary directory tree as follow:

From there, you would like to populate a PHP array with the directory names as keys, nesting them to represent the depth of each sub-directory. Something like this:

First things first, we need to create these directories. Easy peasy! Open a terminal, go in your filesystem where the root directory should be, and run this one-liner:

To guarantee your success, you’ll need these functions, too. Copy them where you’ll implement your solution:

We can first try to solve the problem using iterative loops. Remember, even if we defined an arbitrary example, the depth could go on an on.

Don’t spend too much time on your iteration. It might be possible using a stack, but I didn’t really try. You’ll see the likely failed attempt developers will usually do below:

This solution would works if we knew the depth of the directory tree. Since we don’t, we don’t know either how deep we need to loop.

The Base case

Let’s write the base case. What would be the easiest case we could solve?

The easiest case to solve would be a directory without any sub-directory.

To understand better the problem, the structure of a filesystem can be displayed as a tree data structure. Recursion is very well suited to parse this kind of data structure.

Here it is:

The dotted lines are there to remind us that there could be even more sub-directories going down.

Now that we have a clear visual representation of our problem, let’s decompose it even more:

  • For example, the directory dirs has three direct sub-directories, 1 , 2 , 3 , but it could have more.
  • For example, the path from the node dirs to the node 2-1-1-2-1 could be even deeper. There could be another subdirectory 2-1-1-2-1-1 , for example.

The first point can be easily solved. I gave you the function subDirectories($path) which will give you every direct children of a directory. We can use an iterative loop to parse them.

The second point is more tricky to solve. This is where we need recursion. We could imagine going deeper and deeper in the tree for each sub-directory using recursion, until we reach a leaf node, which is as well our base case.

We could create an array for each level we go through, and when we reach a leaf-node, we nest every array we created into each other.

I think we have now all the information we need to implement the recursive steps.

Don’t worry if it feels too difficult for you or Davina. It can be tricky to think in term of recursion when you’re used to write iterations. Focus, give it a good try, and even if you don’t succeed, it will bring you closer to the breakthrough you’ll have one day. I promise.

What’s happening here?

  • Line 4 : we create a new array. It will be the array for this level of directories, including every sub-directory.
  • Line 5 to 7 : we have our base case.
  • Line 9 : we begin to iterate through every sub-directory of the current directory.
  • Line 11 : the recursive process begins. For each sub-directory, we go a level deeper by updating the $path , and give as argument the sub-directories of the new path.
  • Line 5 : When we reached our base case for every branch of the tree, we return an empty array. Every array created during the expansion will be returned too, nesting one into another.
  • Line 14 : Finally, we return our nested array after going through every branch of the tree.

Here’s an optional exercise: what about implementing recursiveDisplayDirectories using only recursion, without the foreach ?

Is Recursion Still a Mystery?

Davina is delighted to have solved her problem, and you’re happy to have, again, helped a colleague who needed it.

There are more to know about recursion, especially regarding performances (memory used and time to execute). The last example didn’t include many levels of sub-directories, but if you have more of them, you can end up consuming way too much memory.

Some languages, like Haskell or some LISP dialects, specifically optimize some form of recursion to make it faster while using less memory. It’s called tail call optimization . The performances can be very close to an iterative loop. If you want me to speak about that and in what cases it applies, shout out in the comment.

If you want more exercises, you can contact me. I’m on social media (you’ll find them on the about page ), or you can let a comment.

What did we learn together?

  • Recursion is a way to divide a problem into smaller sub-problems. The solution should solve every sub-problem, one by one.
  • A recursive solution to a problem must have two steps: the base case (the smallest problem to solve) and the recursive steps (applying the same solution over and over till we reach the base case).
  • Iteration can be used instead of recursion. Yet, recursive solutions can be simpler for specific types of problem, like tree-shaped data structure or data structures with unknown depth.
  • Structure And Interpretation Of Computer Program (1.2) - Abelson, Sussman
  • Recursion - Jeff Erickson

enjoyalgorithms

EnjoyMathematics

Fundamentals of Recursion in Programming

Recursion is a widely used idea in data structures and algorithms to solve complex problems by breaking them down into simpler ones. In this blog, we will understand the basic concepts of recursion and help you refine one of the critical problem-solving skills in data structures and algorithms.

What do you mean by recursion?

Recursion means "solving a problem using the solution of smaller subproblems (a smaller version of the same problem)" or "defining a problem in terms of itself."

Recursion comes up in mathematics frequently, where we can find many examples of expressions written in terms of themselves. For example, calculating the value of the nth factorial and the nth Fibonacci numbers is one of the best examples. But recursion is just as much a programming concept!

  • Finding the nth Factorial: n! = n * (n - 1)!
  • Finding the nth Fibonacci: F(n) = F(n - 1) + F(n - 2)

How recursion works in real life?

Suppose you are standing in a long queue of people. How many people are directly behind you in the line? How can we solve this problem recursively?

  • One person can see only the person standing directly in front and behind. So, one can't just look back and count.
  • Each person is allowed to ask questions from the person standing in front or behind.
  • You look behind and see if there is a person there. If not, then you can return the answer "0". If there is a person, repeat this step and wait for a response from the person standing behind.
  • Once a person receives a response, they add 1 and respond to the person that asked them or the person standing in front of them.

Real life examples and logical pattern of recursion

How does recursion works in programming?

In programming terms, recursion is a function calling itself until a "base condition" is true to produce the correct output. In other words, to solve a problem, we solve a problem that is a smaller instance of the same problem, and then use the solution to that smaller instance to solve the original problem.

For a recursive algorithm to work, smaller subproblems must eventually arrive at the base case. In simple words, any recursive algorithm has two parts: the base case and the recursive structure.

The base case is a terminating condition where a function immediately returns the result. This is the smallest version of the problem for which we already know the solution.

Recursive structure  

The recursive structure is an idea to design a solution to a problem via the solution of its smaller sub-problems, i.e., the same problem but for a smaller input size. We continue calling the same problem for smaller input sizes until we reach the base case of recursion.

Steps of problem-solving using recursion

  • Define the base case: Think of the smallest version of the problem and write down the solution.
  • Define the recursive structure: Assume we have a function to solve a problem of the given input size. Now we need to think: How could we use the problem's solution for a smaller input size to solve the problem for the given input size? In other words, how can we combine the solutions of the smaller subproblems to get the solution to the larger problem?
  • Combine the base case and the recursive structure to generate a complete solution to the problem.

Ideas to keep in mind while working with recursion

  • Our code must cover all valid instances of smaller input sizes.
  • We must have a correct base case that makes no recursive calls.
  • When we make a recursive call, it should call a smaller instance and progress towards the base case.
  • When we have a correct recursive structure and base case, then recursion would solve the problem for us. This is a " recursive leap of faith " where we should not worry about the intermediate steps of the recursive calls. Think!

Basic examples of recursive functions

Calculate the sum of two numbers using recursion, calculate the product of two numbers using recursion, calculate the power of two numbers using recursion, understanding recursion via finding nth factorial.

The factorial of a non-negative integer is a multiplication of all integers smaller than or equal to n. For example. the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120

Recursive structure

According to the mathematical definition of the factorial of n, we can write:

If we calculate the value of the  (n - 1)th  factorial, we can easily calculate the value of the  nth  factorial. It means we can solve the problem of input size  n  with its smaller problem of the input size  (n - 1) . In other words, we can solve this problem by using the idea of recursion!

Suppose the function  fact(n)  and  fact(n - 1)  return the value of the  nth  and  (n - 1)th  factorial, respectively. Then we can write the following recursive structure:

In every recursive solution, there must be a terminating condition or base case where our recursion will directly give us results without breaking it again into the sub-problem. If we observe the above recursive structure, then we find the following chain of recursive calls behind the scene: 

The factorial of a negative integer is not defined in the context of natural numbers. So fact(0) is the smallest version of the factorial problem where our recursion will terminate and return the value directly i.e. if n = 0, recursion will return the value 1.

Recursive pseudocode of nth Factorial

How recursion works in the background.

If we draw the flow of recursion for the factorial program, one can find this pattern: we are calling fact(0) last, but it is returning the value first. Similarly, we are calling fact(n) first, but it is returning the value last.

Did you find some  Last In First Out (LIFO)  orders for recursive calls and return values? Yes, you got it right! Behind the scene, the compiler uses a stack data structure to simulate recursion and deliver the correct output. We call this stack:  Call Stack!

  • Order of recursive calls: larger problem to smaller problem
  • fact(n) -> fact(n - 1) -> ... -> fact(i) -> ... -> fact(1) -> fact(0)
  • Order of return values: smaller problem to larger problem
  • fact(0) -> fact(1) -> ... -> fact(i) -> ... -> fact(n - 1) -> fact(n)

How does the idea of the call stack work in recursion?

  • The information about the execution of a recursive function is stored in the call stack. It contains details about the execution: the current state of the function control flow, local variables, and other internal information.
  • During the recursion, when the function calls the same function for a smaller input size, memory is allocated to it, and it goes to the top of the call stack. 
  • In other words, the memory for a called function is allocated on top of the memory allocated for the calling function, and a different copy of local variables is created for each function call.
  • When the base case is reached, the function returns its value to the function by which it is called, memory is deallocated, and the process continues.

Visualization for calculating fact(5) using recursion

Visualisation of recursion using call stack

Examples of some famous recursive algorithms

Reverse an array.

Recursive structure: reverse (A[], l, r) = swap(A[l], A[r]) + reverse(A, l + 1, r - 1).

Base case: if (l >= r) then return.

Recurrence relation: T(n) = T(n - 2) + c, Time complexity = O(n).

Finding the GCD of two numbers

Recursive structure: GCD(a, b) = GCD(b, a mod b), here a > b.

Base case: GCD(a, 0) = a.

Recurrence relation: T(n) = T(n/d) + c, where d is a decreasing factor, Time complexity = O(log b).

Finding the nth Fibonacci

Recursive structure: fib(n) = fib(n - 1) + fib(n - 2).

Base case: We have 2 base cases: fib(0) = 0 and fib(1) = 1.

Recurrence relation: T(n) = T(n - 1) + T(n - 2) + c, Time complexity = O(2^n).

Tower of Hanoi problem

Recursive structure: We move a stack of n disks from peg X to Y using peg Z

Base case: If n = 1, move disk from X to Y.

Recurrence relation: T(n) = 2 T(n - 1) + c, Time complexity = O(2^n).

Binary Search Algorithm

Base case: If (l > r) then return -1.

Recurrence relation: T(n) = T(n/2) + c, Time complexity = O(log n).

Merge Sort Algorithm

Base case: if (l == r) then return. This is a case of a single-element array.

Recurrence relation: T(n) = 2 T(n/2) + cn, Time complexity = O(nlogn).

Quick Sort Algorithm

Recurrence relation: T(n) = Sum (i = 0 to n - 1) [T(i) + T(n - i - 1)]/ n, Time complexity = O(nlogn) [Average case analysis].

Reverse a Linked List

Base case: if (head == NULL || head->next == NULL), return head.

Recurrence relation: T(n) = T(n - 1) + c, Time complexity = O(n).

Post-order Traversal of a Binary Tree

Base case: if(root == NULL), then return.

Print all permutation of a given string

Base case: if(l == r) then print(A).

Recurrence relation: T(n) = sum (i = 0 to n - 1) [T(n - i) + c], Time complexity = O(n!).

Stack overflow error in recursion

When we call a recursive function, the return address and arguments are pushed onto the call stack. The stack is finite, so if the recursion is too deep, you'll eventually run out of stack space. This is also called the stack overflow in recursion. In some situations, if the recursive function is tail-recursive, some compilers might optimize the recursive call away by turning it into a jump. Popular reasons for stack overflow error:

  • The recursive function is written with a missing base case. 
  • A recursive function call with an incorrect base case.

Common mistakes in recursive implementations

Here are two common ways that a recursive implementation can go wrong:

  • The base case is missing entirely, or the problem needs more than one base case, but not all the base cases are covered.
  • The recursive step doesn’t reduce to a smaller subproblem, so the recursion doesn’t converge.

Look for these when you are debugging. On the bright side, an infinite loop in an iterative implementation usually becomes a stack overflow error in a recursive implementation. A buggy recursive program fails faster!

Analysis of recursive algorithms

The basic idea of recursion analysis is: Calculate the total number of operations performed by recursion at each recursive call and do the sum to get the overall time complexity. So when recursion is doing constant operation at each recursive call, we just count the total number of recursive calls. Otherwise, the analysis will be a little mathematical if the operation count at each recursive call depends on the input size.

Overall, there are several techniques to analyze recursion: Substitution method, Recursion tree method, and Master theorem.

  • The recursion tree method is one of the most popular and fundamental approaches to analysis, where we define recurrence relation, draw a recursion tree, calculate the cost of each level, and do level by level sum to get the overall time complexity.
  • The substitution method is a simple idea: We write the recurrence relation function in terms of input size and substitute the value for a smaller input size to get a mathematical series in terms of n. This method works best for some simple recursive functions, but mathematical series can be complex to calculate for some functions.
  • The master theorem is one of the most popular techniques which can only be applied to analyze  divide and conquer algorithms .

Explore this blog to learn recursion analysis : Analysis of Recursion in data structure and algorithms

Recursion Vs. Iteration

  • Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure, while recursion achieves repetition through repeated method calls.
  • Iteration and recursion each involve a termination case: Iteration terminates when the loop condition becomes false, and recursion terminates when a base case is reached.
  • Iteration and recursion can both result in infinite repetition: An infinite loop occurs with iteration if the loop condition always evaluates to true, while infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on the base case.
  • Recursion repeatedly invokes method calls to smaller problems, and consequently, there is an overhead of method calls. This can be expensive in both processor time and memory space.

Explore this blog for more details: Iteration vs Recursion comparison

Application of recursion in problem-solving 

  • Divide and conquer approach
  • Solving searching and sorting algorithms
  • Solving dynamic programming problems
  • Problem-solving using Backtracking
  • Solving linked list problems
  • Solving tree problems using DFS
  • Solving graph problems using DFS
  • Designing approximation algorithms

Concepts to explore further

  • Types of recursion
  • Tail recursion and recursive optimization
  • The idea of functional programming

Coding problems to practice using recursion

  • Josephus problem
  • Quick-select algorithm to find the kth smallest element
  • Recursive binary tree traversals
  • Find all possible combinations of K numbers from 1 to n
  • Find kth smallest element of two sorted arrays
  • Median of two sorted arrays
  • Flood fill problem
  • N-Queen problem
  • Karatsuba algorithm

Content references

  • Algorithms by CLRS
  • The Algorithm Design Manual by Steven Skiena

If you have any queries/doubts/feedback, please write us at [email protected]. Enjoy learning, Enjoy algorithms!

Share Your Insights

Don’t fill this out if you’re human:

More from EnjoyAlgorithms

Self-paced courses and blogs, coding interview, machine learning, system design, oop concepts, our newsletter.

Subscribe to get well designed content on data structure and algorithms, machine learning, system design, object orientd programming and math.

©2023 Code Algorithms Pvt. Ltd.

All rights reserved.

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Recursion Practice Problems with Solutions

Here’s what Google has to say on recursion – Did you mean: recursion

Recursion

Strange, isn’t? Or not!!

  Recursion is a problem-solving technique that involves breaking a problem into smaller and simpler problems of the same kind (also called subproblems) until we get a small enough subproblem having a trivial solution. We can say that recursion is “defining a problem in terms of itself” as it involves a function calling itself with a base case to terminate the infinite loop.

Recursion has two main components: the base case and the recursive case. The base case is the simplest or smallest problem that can be solved directly without recursion. The recursive case is the larger or more complex problem that can be solved by calling the same function with smaller or simpler inputs.

Recursion is an important concept in computer science and a very powerful tool in writing algorithms. It allows us to write very elegant solutions to problems that may otherwise be very difficult to implement iteratively. It might be a little confusing and difficult to understand, especially for beginners but once you understand it, a whole new world of programming will open for you. Recursion just takes practice to get good at and nothing is more interesting than finding a solution to a problem the recursive way.

Backtracking:

  • Find all combinations of elements satisfying given constraints Medium
  • K–Partition Problem | Printing all partitions Hard
  • Find all distinct combinations of a given length with repetition allowed Medium
  • Print all combinations of numbers from 1 to n having sum n Medium
  • Print all possible solutions to N–Queens problem Hard
  • Print all possible Knight’s tours on a chessboard Hard
  • Find the shortest path in a maze Medium
  • Find the longest possible route in a matrix Medium
  • Find the path from source to destination in a matrix that satisfies given constraints Medium
  • Find the total number of unique paths in a maze from source to destination Medium
  • Magnet Puzzle Hard
  • Find all paths from the first cell to the last cell of a matrix Medium
  • Print all shortest routes in a rectangular grid Medium
  • Find all occurrences of the given string in a character matrix Hard
  • Generate a list of possible words from a character matrix Hard
  • Find all permutations of a string – C++ , Java , Python Hard
  • Print all distinct subsets of a given set Hard
  • Check if a string is a rotated palindrome or not Medium
  • Check if a repeated subsequence is present in a string or not Hard
  • Find all interleaving of given strings Easy
  • Find all possible combinations of words formed from the mobile keypad Hard
  • Find all possible combinations by replacing given digits with characters of the corresponding list Hard
  • Find all strings of a given length containing balanced parentheses Medium
  • Find all combinations of non-overlapping substrings of a string Medium
  • Determine whether a string is a palindrome or not Easy
  • Print all combinations of phrases formed by picking words from each of the given lists Medium
  • Break a string into all possible combinations of non-overlapping substrings Medium
  • Remove adjacent duplicate characters from a string Easy
  • Find all n-digit strictly increasing numbers (Bottom-up and Top-down approach) Medium
  • Find all n-digit binary numbers having more 1’s than 0’s for any prefix Medium
  • Find all n-digit numbers with a given sum of digits Hard
  • Find all n-digit binary numbers with an equal sum of bits in their two halves Hard
  • Find all n-digit numbers with equal sum of digits at even and odd indices Hard
  • Find all lexicographic permutations of a string Hard
  • Reverse a string using recursion Easy
  • Number to word conversion Hard
  • Implement strstr function in Java Easy
  • Find the minimum number possible by doing at-most k swaps Medium
  • Determine whether a string matches with a given pattern Hard
  • Replace every array element with the product of every other element Medium
  • Find all distinct combinations of a given length – I Medium
  • Find all distinct combinations of a given length – II Medium
  • Find a triplet with the given sum in an array Medium
  • Reverse every consecutive m -elements of a subarray Medium
  • Maximum Product Subset Problem Easy
  • 4–Sum Problem | Quadruplets with a given sum Medium
  • Quickselect Algorithm Medium
  • Add elements of two arrays into a new array Easy
  • Print all combinations of positive integers in increasing order that sums to a given number Hard
  • 3–partition problem extended | Printing all partitions Hard
  • Check if an array represents a min-heap or not Medium
  • Convert max heap to min heap in linear time Easy
  • Find the odd occurring element in an array in logarithmic time Medium
  • Generate the power set of a given set Medium
  • Print matrix in spiral order Medium
  • Replace all occurrences of 0 that are not surrounded by 1 in a binary matrix Medium
  • Young Tableau | Insert, Search, Extract-Min, Delete, Replace Hard
  • Replace all occurrences of 0 that are surrounded by 1 in a binary matrix Medium
  • Sort an array using Young tableau Hard
  • Flood Fill Algorithm Medium
  • Find the shortest path from source to destination in a matrix that satisfies given constraints Hard
  • Find minimum passes required to convert all negative values in a matrix Hard

Divide & Conquer:

  • Binary Search Algorithm Easy
  • Find the number of rotations in a circularly sorted array Easy
  • Find the smallest missing element from a sorted array Medium
  • Find the number of 1’s in a sorted binary array Easy
  • Find the peak element in an array Medium
  • Maximum Subarray Sum using Divide and Conquer Medium
  • Find floor and ceil of a number in a sorted array (Recursive solution) Easy
  • Find the frequency of each element in a sorted array containing duplicates Easy
  • Find the minimum and maximum element in an array using Divide and Conquer Easy
  • Longest Common Prefix (LCP) Problem Easy
  • Exponential search Easy
  • Unbounded Binary Search Easy
  • Efficiently implement power function Easy

Linked List:

  • Clone a Linked List Easy
  • Delete a linked list Easy
  • Split a linked list into two lists where each list contains alternating elements from it Medium
  • Construct a linked list by merging alternate nodes of two given lists Easy
  • Merge two sorted linked lists into one Medium
  • Efficiently merge k sorted linked lists Hard
  • Reverse a Linked List – Recursive Solution Hard
  • Reverse every group of k nodes in a linked list Medium
  • Find k’th node from the end of a linked list Easy
  • Merge alternate nodes of two linked lists into the first list Medium
  • Delete every N nodes in a linked list after skipping M nodes Easy
  • Rearrange linked list in a specific manner in linear time Medium
  • Check if a linked list is palindrome or not Medium
  • Move the last node to the front of a linked list Easy
  • Rearrange a linked list by separating odd nodes from even ones Medium
  • Recursively check if the linked list of characters is palindrome or not Medium
  • Add a single-digit number to a linked list representing a number Medium
  • Reverse every alternate group of k nodes in a linked list Medium
  • Determine whether a linked list is palindrome or not Medium
  • Reverse a doubly linked list Easy
  • Pairwise swap adjacent nodes of a linked list Medium
  • Flatten a Linked List Hard
  • Check if a linked list of strings is palindromic Easy
  • Flatten a multilevel linked list Medium
  • Clone a linked list with random pointer Hard
  • Update random pointer for each linked list node to point to the maximum node Medium
  • Insertion Sort Algorithm Easy
  • Selection Sort Algorithm Easy
  • Bubble Sort Algorithm Easy
  • Merge Sort Algorithm Easy
  • Quicksort Algorithm Medium
  • Hybrid QuickSort Algorithm Medium
  • Quicksort using Dutch National Flag Algorithm Medium
  • Quicksort algorithm using Hoare’s partitioning scheme Medium
  • Heap Sort Algorithm Medium
  • Introsort Algorithm – Overview and C++ Implementation Hard
  • Merge sort algorithm for a singly linked list Hard
  • Sort a doubly-linked list using merge sort Medium
  • Inversion count of an array Hard
  • Find surpasser count for each array element Hard
  • Water Jugs Problem Hard

Binary Tree:

  • Inorder Tree Traversal Medium
  • Preorder Tree Traversal Medium
  • Postorder Tree Traversal Medium
  • Check if two binary trees are identical or not Easy
  • Print bottom view of a binary tree Medium
  • Print top view of a binary tree Medium
  • In-place convert a binary tree to its sum tree Easy
  • Determine whether the given binary tree nodes are cousins of each other Medium
  • Print cousins of a given node in a binary tree Medium
  • Check if a binary tree is a sum tree or not Medium
  • Combinations of words formed by replacing given numbers with corresponding alphabets Hard
  • Determine whether a binary tree is a subtree of another binary tree Medium
  • Find the diameter of a binary tree Medium
  • Check if a binary tree is symmetric or not Easy
  • Convert a binary tree to its mirror Easy
  • Determine if a binary tree can be converted to another by doing any number of swaps of children Easy
  • Find the Lowest Common Ancestor (LCA) of two nodes in a binary tree Medium
  • Print all paths from the root to leaf nodes of a binary tree Easy
  • Find ancestors of a given node in a binary tree Medium
  • Find distance between given pairs of nodes in a binary tree Hard
  • Find the diagonal sum of a binary tree Medium
  • Sink nodes containing zero to the bottom of a binary tree Hard
  • Convert a binary tree to a full tree by removing half nodes Medium
  • Truncate a binary tree to remove nodes that lie on a path having a sum less than k Medium
  • Find maximum sum root to leaf path in a binary tree Medium
  • Check if a binary tree is height-balanced or not Medium
  • Convert binary tree to Left-child right-sibling binary tree Medium
  • Print all paths from leaf to root node of a binary tree Medium
  • Find all nodes at a given distance from leaf nodes in a binary tree Hard
  • Count all subtrees having the same value of nodes in a binary tree Medium
  • Find the maximum difference between a node and its descendants in a binary tree Medium
  • Find the maximum sum path between two leaves in a binary tree Hard
  • Construct a binary tree from inorder and preorder traversal Hard
  • Construct a binary tree from inorder and postorder traversals Hard
  • Construct a binary tree from inorder and level order sequence Hard
  • Construct a full binary tree from the preorder sequence with leaf node information Hard
  • Construct a full binary tree from a preorder and postorder sequence Hard
  • Find postorder traversal of a binary tree from its inorder and preorder sequence Medium
  • Set next pointer to the inorder successor of all nodes in a binary tree Easy
  • Find preorder traversal of a binary tree from its inorder and postorder sequence Hard
  • Find difference between sum of all nodes present at odd and even levels in a binary tree Easy
  • Clone a binary tree with random pointers Hard
  • Threaded Binary Tree – Overview and Implementation Medium
  • Determine if a binary tree satisfies the height-balanced property of a red–black tree Medium
  • Construct an ancestor matrix from a binary tree Easy
  • Find all possible binary trees having the same inorder traversal Hard
  • Perform boundary traversal on a binary tree Medium
  • Check if each node of a binary tree has exactly one child Easy
  • Evaluate a Binary Expression Tree Easy
  • Construction of an expression tree Easy
  • Fix children-sum property in a binary tree Medium
  • Maximum path sum in a binary tree Hard
  • Create a mirror of an m–ary tree Easy
  • Print a two-dimensional view of a binary tree Easy
  • Construct a Cartesian tree from an inorder traversal Medium
  • Calculate the height of a binary tree with leaf nodes forming a circular doubly linked list Medium
  • Link nodes present in each level of a binary tree in the form of a linked list Hard
  • Convert a ternary tree to a doubly-linked list Medium
  • Extract leaves of a binary tree into a doubly-linked list Medium
  • Find the vertical sum of a binary tree Hard
  • In-place convert a binary tree to a doubly-linked list Hard
  • Check whether the leaf traversal of given binary trees is the same or not Hard
  • Efficiently print all nodes between two given levels in a binary tree Easy
  • Calculate the height of a binary tree Easy
  • Delete a binary tree Easy
  • Level order traversal of a binary tree Easy
  • Spiral order traversal of a binary tree Medium
  • Reverse level order traversal of a binary tree Easy
  • Print left view of a binary tree Easy
  • Find the next node at the same level as the given node in a binary tree Medium
  • Check if a binary tree is a complete binary tree or not Medium
  • Print diagonal traversal of a binary tree Medium
  • Invert Binary Tree Easy
  • Convert a binary tree into a doubly-linked list in spiral order Hard
  • Check if a binary tree is a min-heap or not Medium
  • Invert alternate levels of a perfect binary tree Hard
  • Perform vertical traversal of a binary tree Medium
  • Compute the maximum number of nodes at any level in a binary tree Easy
  • Print right view of a binary tree Medium
  • Find the minimum depth of a binary tree Easy
  • Print nodes of a binary tree in vertical order Medium

Binary Search Tree:

  • Insertion in a BST Easy
  • Search a given key in BST Easy
  • Deletion from BST (Binary Search Tree) Medium
  • Construct a balanced BST from the given keys Easy
  • Determine whether a given binary tree is a BST or not Medium
  • Check if the given keys represent the same BSTs or not without building BST Hard
  • Find inorder predecessor for the given key in a BST Medium
  • Find the Lowest Common Ancestor (LCA) of two nodes in a BST Easy
  • Find k’th smallest and k’th largest element in a BST Easy
  • Find floor and ceil in a Binary Search Tree Medium
  • Convert a binary tree to BST by maintaining its original structure Medium
  • Remove nodes from a BST that have keys outside a valid range Medium
  • Find a pair with the given sum in a BST Easy
  • Find k’th smallest node in a Binary Search Tree (BST) Easy
  • Find inorder successor for the given key in a BST Medium
  • Fix a binary tree that is only one swap away from becoming a BST Hard
  • Update every key in a BST to contain the sum of all greater keys Medium
  • Check if a given sequence represents the preorder traversal of a BST Hard
  • Build a Binary Search Tree from a postorder sequence Hard
  • Build a Binary Search Tree from a preorder sequence Hard
  • Count subtrees in a BST whose nodes lie within a given range Medium
  • Find the size of the largest BST in a binary tree Hard
  • Print complete Binary Search Tree (BST) in increasing order Easy
  • Print binary tree structure with its contents in C++ Medium
  • Treap Data Structure Beginner
  • Implementation of Treap Data Structure (Insert, Search, and Delete) Hard
  • Merge two BSTs into a doubly-linked list in sorted order Hard
  • Construct a height-balanced BST from an unbalanced BST Hard
  • Construct a height-balanced BST from a sorted doubly linked list Hard
  • Find a triplet with the given sum in a BST Hard
  • Convert a Binary Search Tree into a Min Heap Hard

Dynamic Programming:

  • Longest Common Subsequence Problem Medium
  • Longest Common Subsequence of k–sequences Medium
  • Longest Common Subsequence | Finding all LCS Hard
  • Longest Palindromic Subsequence using Dynamic Programming Medium
  • Longest Repeated Subsequence Problem Medium
  • Implement Diff Utility Medium
  • Shortest Common Supersequence Problem Medium
  • Shortest Common Supersequence | Finding all SCS Hard
  • Shortest Common Supersequence Problem using LCS Hard
  • Longest Increasing Subsequence using Dynamic Programming Hard
  • Longest Decreasing Subsequence Problem Hard
  • Maximum Sum Increasing Subsequence Problem Medium
  • The Levenshtein distance (Edit distance) Problem Medium
  • Find the size of the largest square submatrix of 1’s present in a binary matrix Medium
  • Matrix Chain Multiplication using Dynamic Programming Hard
  • Find minimum cost to reach the last cell of a matrix from its first cell Medium
  • Find the longest sequence formed by adjacent numbers in the matrix Medium
  • Count the number of paths in a matrix with a given cost to reach the destination cell Medium
  • 0–1 Knapsack Problem Medium
  • Partition Problem using Dynamic Programming Medium
  • Subset Sum Problem – Dynamic Programming Solution Medium
  • 3–Partition Problem Medium
  • Minimum Sum Partition Problem Hard
  • Rod Cutting Problem Medium
  • Maximum Product Rod Cutting Medium
  • Coin change-making problem Medium
  • Coin Change Problem Hard
  • Total possible solutions to a linear equation of k variables Hard
  • Longest Alternating Subsequence Problem Medium
  • Count the number of times a pattern appears in a given string as a subsequence Hard
  • Collect maximum points in a matrix by satisfying given constraints Hard
  • Find all N-digit binary strings without any consecutive 1’s Easy
  • Count total possible combinations of n-digit numbers in a mobile keypad Medium
  • Word Break Problem – Dynamic Programming Hard
  • Check if a string is k–palindrome or not Hard
  • Find total ways to achieve a given sum with n throws of dice having k faces Medium
  • Wildcard Pattern Matching Hard
  • Find the number of ways to fill an N × 4 matrix with 1 × 4 tiles Medium
  • Ways to reach the bottom-right corner of a matrix with exactly k turns allowed Hard
  • Weighted Interval Scheduling Problem Medium
  • Find total ways to reach n’th stair with at-most m steps Medium
  • Find total ways to reach the n’th stair from the bottom Medium
  • Find the minimum number of deletions required to convert a string into a palindrome Medium
  • Pots of Gold Game Problem using Dynamic Programming Hard
  • Find minimum cuts needed for the palindromic partition of a string Hard
  • Find minimum jumps required to reach the destination Medium
  • Find the probability that a person is alive after taking n steps on an island Medium
  • Longest Increasing Subsequence using LCS Medium
  • Count all paths in a matrix from the first cell to the last cell Easy
  • Check if a string matches with the given wildcard pattern Hard
  • Check if a string is interleaving of two other given strings Medium
  • Find all employees who directly or indirectly reports to a manager Hard
  • Find optimal cost to construct a binary search tree Hard
  • Find the maximum sum of a subsequence with no adjacent elements Medium
  • Minimum-weight triangulation of a convex polygon Hard
  • Find maximum profit that can be earned by conditionally selling stocks Easy
  • Program to find n’th Fibonacci number Easy
  • Count decodings of a given sequence of digits Medium
  • Hat Check Problem – Counting Derangements Medium
  • Maximum Independent Set Problem Medium
  • Find the minimum number of squares that sum to a given number Medium
  • Truncate an integer array such that 2×min becomes more than max Hard
  • Find ways to calculate a target from elements of the specified array Medium
  • Find the length of the longest path in a matrix with consecutive characters Medium
  • Collect maximum value of coins in a matrix Hard
  • Single-Source Shortest Paths – Bellman–Ford Algorithm Medium
  • All-Pairs Shortest Paths – Floyd Warshall Algorithm Easy

Programming Puzzles:

  • Implement power function without using multiplication and division operators Easy
  • Print all numbers between 1 to N without using a semicolon Medium
  • Determine the if condition to print the specific output Easy
  • Tower of Hanoi Problem Medium
  • Print all numbers between 1 to N without using any loop | 4 methods Easy
  • Multiply two numbers without using a multiplication operator or loops Easy
  • Find minimum number without using conditional statement or ternary operator Medium
  • Perform division of two numbers without using division operator Medium
  • Find maximum number without using conditional statement or ternary operator Easy
  • Depth First Search (DFS) Medium
  • Breadth-First Search (BFS) Medium
  • Arrival and departure time of vertices in DFS Easy
  • Determine whether a graph is Bipartite using DFS Medium
  • Topological Sort Algorithm for DAG Medium
  • Transitive closure of a graph Easy
  • Determine whether an undirected graph is a tree (Acyclic Connected Graph) Medium
  • 2–Edge Connectivity in a graph Hard
  • Check if a digraph is a DAG (Directed Acyclic Graph) or not Medium
  • Disjoint–Set Data Structure (Union–Find Algorithm) Medium
  • Check if a graph is strongly connected or not Easy
  • Check if a graph is strongly connected or not using one DFS Traversal Hard
  • Union–Find Algorithm for cycle detection in a graph Medium
  • Find the cost of the shortest path in DAG using one pass of Bellman–Ford Medium
  • Find all Possible Topological Orderings of a DAG Hard
  • Find correct order of alphabets in a given dictionary of ancient origin Hard
  • Find the longest path in a Directed Acyclic Graph (DAG) Hard
  • Print all k–colorable configurations of a graph (Vertex coloring of a graph) Medium
  • Print all Hamiltonian paths present in a graph Hard
  • Kruskal’s Algorithm for finding Minimum Spanning Tree Hard
  • Eulerian cycle in directed graphs Hard
  • Find root vertex of a graph Medium
  • Check whether an undirected graph is Eulerian Medium
  • Check if a set of words can be rearranged to form a circle Hard
  • Find itinerary from the given list of departure and arrival airports Easy
  • Check if an undirected graph contains a cycle or not Medium
  • Compute the least cost path in a weighted digraph using BFS Medium
  • Find the path between given vertices in a directed graph Easy
  • Recursive solution to sort a stack Hard
  • Reverse a stack using recursion Hard
  • Reverse a string using a stack data structure Easy
  • Reverse an array in C++ Easy
  • Find all binary strings that can be formed from a wildcard pattern Medium
  • Implement a stack using the queue data structure Medium
  • Implement a queue using the stack data structure Medium
  • Lexicographic sorting of a given set of keys Medium
  • Find the maximum occurring word in a given set of strings Easy
  • Find first k maximum occurring words in a given set of strings Medium
  • Word Break Problem – Using Trie Data Structure Medium
  • Find all words matching a pattern in the given dictionary Medium
  • Find the shortest unique prefix for every word in an array Medium

Rate this post

Average rating 4.76 /5. Vote count: 143

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

guest

Mathwarehouse Logo

How to Solve Recursive Sequences

What is a recursive sequence.

A Recursive Sequence is a function that refers back to itself. Below are several examples of recursive sequences.

For instance, $$ {\color{red}f}(x) = {\color{red}f}(x-1) + 2 $$ is an example of a recursive sequence because $$ {\color{red}f}(x)$$ defines itself using $$ {\color{red}f}$$.

Examples of Recursive Math sequences

Visualization of a Recursive sequence

Pascal's Triangle is one of the most famous recursive sequences in mathematics. Below is a visualization of how Pascal's Triangle works. As you can see each term in the triangle is a result of adding two other 'parts' of the triangle.

See more math gifs here

Recursive sequences often cause students a lot of confusion. Before going into depth about the steps to solve recursive sequences, let's do a step-by-step examination of 2 example problems. After that, we'll look at what happened and generalize the steps .

Calculate $$ f(7) $$ for the recursive sequence $$ f(x) = 2 \cdot f(x - 2) + 3 $$ which has a seed value of $$ f(3) = 11 $$.

Calculate $$ f(8)$$ for the recursive sequence $$ f(x) = 4 \cdot f(x - 3) + 1 $$ which has a seed value of $$f(2) = 9 $$.

The Two "Phases" of solving recursion problems

Let's explore the two phases of solving recursive sequences:

phase of I of recursion example 2

Can you determine why the sequence below is 'unsolvable'?

unsolvable math recursion problem example

Look at the problem step by step to see why you can not solve this problem.

This example is one of the most famous recursive sequences and it is called the Fibonacci sequence. It also demonstrates how recursive sequences can sometimes have multiple $$ f(x)$$'s in their own definition.

It is defined below.

$$ f(x) = f(x-1) + f(x-2) $$

Practice Problem 1

Given the recursive sequence $$ f(x) = 2\cdot f(x-1) +3 $$ and $$ f({\color{red}4}) = {\color{blue}2} $$, evaluate $$f(6) $$ .

Keep re-substituting until you reach the seed value ($$ f({\color{red}4}) = {\color{blue}2}$$).

We hit the 'seed' value so we are done with the first "phase".

Substitute back up the "chain" using actual values.

Below is the step by step work:

Practice Problem 2

Solve the recursive sequence $$ f(x) = 5\cdot f(x + 2) - 3 $$ and $$ f({\color{red} 12 }) = {\color{blue}-4} $$, calculate $$f(8) $$ .

Keep re-substituting until you reach the seed, value ($$ f({\color{red}12}) = {\color{blue}-4}$$).

Below is the step by step work.

Practice Problem 3

If a sequence is defined recursively by $$ f(0) = 2 $$ and $$ f(x+1) = -2 \cdot f(x) +3 $$ for $$ x \ge 0$$, then solve for $$f(2) $$.

This question was taken from Algebra I (Common Core) Regents exam from June 2015 (Question #20)

Keep re-substituting until you reach the seed value ($$ f({\color{red}0}) = {\color{blue}2}$$).

Practice Problem 4

Solve the recursive sequence $$ f(x) = f(x - 2) + 11 $$ and $$ f({\color{red}1}) = {\color{blue}5} $$, calculate $$f(3) $$ .

Keep re-substituting until you reach the seed value ($$ f({\color{red}1}) = {\color{blue}5}$$).

Ultimate Math Solver (Free) Free Algebra Solver ... type anything in there!

Popular pages @ mathwarehouse.com.

Surface area of a Cylinder

How to build up an intuition for recursion

by Dawson Eliasen

And how to use it to solve problems

8aza4Gl8EaNwkDwVTGejjq-QqNXHIHXNNIO-

Recursion is one of the most intimidating topics that students face in programming. It’s hard to understand because the human brain is not capable of performing recursion — but computers are. This is exactly why recursion is such a powerful tool for programmers, but it also means that learning how to use it is exceedingly difficult. I want to help you build an intuition for recursion so you can use it to solve problems.

I am a teaching assistant for the introductory computer science course at my university. I’ve explained recursion in exactly the same way a dozen times this week. My explanation seems to help most students. This article has the most general explanation at the top, and the most specific explanation at the bottom. This way, you can start at the beginning and stop as soon as you feel you understand recursion well enough. I’ve provided some examples in Java, and they are simple enough that anyone with some programming experience can interpret them.

What is Recursion?

To understand recursion, let’s take a step back from programming. Let’s start by establishing a general definition for the term. Something is recursive if it is defined by its own definition to some extent. That probably doesn’t help you understand recursion very much, so let’s look at a mathematical definition. You are familiar with functions — one number goes in, another number comes out. They look like this:

Let’s change this idea slightly and instead think about a sequence. A sequence takes an integer number, and an integer number comes out.

Sequences can be thought of as functions with inputs and outputs that are limited to only positive integers. Generally, sequences start with 1. This means that A(0) is 1. The sequence above is the following:

A(n) = 1, 2, 4, 6, 8, 10, … where n = 0, 1, 2, 3, 4, 5, …

Now, consider the following sequence:

A(n) = 2 x A(n-1)

This sequence is recursively defined. In other words, the value any given element depends on the value of another element. This sequence looks like this:

A(n) = 1, 2, 4, 8, 16, … where n = 0, 1, 2, 3, 4, …

Any element is defined as 2 times the previous element.

  • The n = 4 element, 16, is defined as 2 times the previous element.
  • The n = 3 element, 8, is defined as 2 times the previous element.
  • The n = 2 element, 4, is defined as 2 times the previous element.
  • The n = 1 element, 2, is defined as 2 times the previous element.
  • The n = 0 element, 1, is defined as…

The n = 0 element cannot be recursively defined. There is no previous element. We call this a base case , and it is a necessary consequence of recursive definitions. They must be explicitly represented in your code . We could represent this recursive sequence in Java like so:

You should familiarize yourself with the anatomy of a recursive method. Note the base case: if n is 0, the element is defined as 1. Otherwise, the element is defined as 2 times the previous element. We must recursively call the method to get the value of the previous element, and then multiply it by 2. All recursive methods will have these two components:

  • Base case, which returns a well-defined value.
  • Recursive case, which returns a recursively defined value.

0E2HqB2n-Uaz7t4xog-zDG5IbGJdTFEuUN9c

Let’s do another example, continuing with the mathematics context. The Fibonacci sequence is often used to illustrate recursion. Any element of the Fibonacci sequence is the sum of the two preceding elements. It goes like this:

F(n) = 1, 1, 2, 3, 5, 8, … where n = 0, 1, 2, 3, 4, 5, …

  • The n = 5, element, 8, is defined as the sum of the n = 4 element and the n = 3 element…

At this point, you should hesitate. In the previous example, each element depended on only one other element, now each element depends on two other elements. This complicates things.

  • The n = 4 element, 5, is defined as the sum of the n = 3 element and the n = 2 element.
  • The n = 3 element, 3, is defined as the sum of the n = 2 element and the n = 1 element.
  • The n = 2 element, 2, is defined as the sum of the n = 1 element and the n = 0 element.
  • The n = 1 element, 1, is defined as the sum of the n = 0 element and…

The n = 1 element cannot be recursively defined. Neither can the n = 0 element. These elements cannot be recursively defined because the recursive definition requires two preceding elements. The n = 0 element has no preceding elements, and the n = 1 element has only one preceding element. This means that there are two base cases. Before writing any code, I would write down something like this:

The n = 0 element is defined as 1. The n = 1 element is defined as 1.

The n element is defined as the sum of the n-1 element and the n-2 element.

Now we have an idea of how this task is recursively defined, and we can go ahead and write some code. Never start writing code without first having a natural understanding of the task.

The Call Stack

1ddahVRxpZNWjPgx-9mfnaEmalc76XpEG175

As programmers, we want to have an intuition for recursion so that we may use it to do things. To do so effectively, we must understand how a computer processes recursion.

There is a data structure that the computer uses to keep track of method calls called the call stack . Each method call creates local variables from the method parameters. The computer needs to store these variables while the method is being executed. Then, the computer ditches the values when the method returns to avoid wasting memory.

The call stack (and stacks in general) function as you might imagine some sort of real-life stack would. Imagine a stack of papers on your desk — it starts as nothing, and then you add papers one by one. You don’t know anything about any of the papers in the stack except for the paper on top. The only way you can remove papers from the stack is by taking them off the top, one-by-one, in the opposite order that they were added .

This is essentially how the call stack works, except the items in the stack are activation records instead of papers. Activation records are just little pieces of data that store the method name and parameter values.

Without recursion, the call stack is pretty simple. Here’s an example. If you had some code that looked like this…

…The call stack would look like this:

Here we see two methods under execution, main and myMethod . The important thing to notice is that main cannot be removed from the stack until myMethod is removed from the stack. In other words, main cannot complete until myMethod is called, executed, and returns a value.

This is true for any case of method composition (a method within a method) — so let’s look at recursive example: the A(int n) method we wrote earlier. Your code might look like this:

When main is called, A is called. When A is called, it calls itself. So the call stack will start building up like so:

A(4) calls A(3) .

Now, it’s important to note that A(4) cannot be removed from the call stack until A(3) is removed from the call stack first. This makes sense, because the value of A(4) depends on the value of A(3) . The recursion carries on…

When A(0) is called, we have reached a base case. This means that the recursion is completed, and instead of making a recursive call, a value is returned. A(0) comes off the stack, and the rest of the calls are then able to come off the stack in succession until A(4) is finally able to return its value to main.

Here’s the intuition: the return value of any method call depends on the return value of another method call. Therefore, all the method calls must be stored in memory until a base case is reached. When the base case is reached, the values start becoming well-defined instead of recursively defined. For example, A(1) is recursively defined until it knows the definition of the base case, 1. Then, it is well-defined as 2 times 1.

When we are trying to solve problems with recursion, it is often more effective to think about the order in which values are returned. This is the opposite of the order in which calls are made. This order is more useful because it consists of well-defined values, instead of recursively defined values.

For this example, it is more useful to consider that A(0) returns 1, and then A(1) returns 2 times 1, and then A(2) returns 2 times A(1) , and so on. However, when we are writing our code, it can easier to frame it in the reverse order (the order that the calls are made). This is another reason that I find it helpful to write the base case and the recursive case down before writing any code.

Helper Methods and Recursion vs. Loops

Aicn9TpaTduZb3eahKIRYtL2DvZzb6cxf6M-

We are programmers, not mathematicians, so recursion is simply a tool. In fact, recursion is a relatively simple tool. It’s very similar to loops in that both loops and recursion induce repetition in the program.

You may have heard that any repetitive task can be done using either a while loop or a for loop. Some tasks lend themselves better to while loops and other tasks lend themselves better to for loops.

The same is true with this new tool, recursion. Any repetitive task can be accomplished with either a loop or recursion, but some tasks lend themselves better to loops and others lend themselves better to recursion.

When we use loops, it is sometimes necessary to make use of a local variable to “keep track” of a calculation. Here’s an example.

This method takes an array of doubles as a parameter and returns the sum of that array. It uses a local variable, sum , to keep track of the working sum. When the loop is completed, sum will hold the actual sum of all values in the array, and that value is returned. This method actually has two other local variables that are less obvious. There is the double array a , whose scope is the method, and the iterator i (keeps track of the index), whose scope is the for loop.

What if we wanted to accomplish this same task using recursion?

This task is repetitive, so it is possible to do it using recursion, though it is probably more elegantly accomplished using a loop. We just need to create a few local variables to keep track of the working sum and the index, right?

Alas, this is impossible. Local variables only exist in the context of a single method call, and recursion makes use of repeated method calls to accomplish a repetitive task. This means that local variables are pretty much useless when we are using recursion. If you are writing a recursive method and you feel as though you need a local variable, you probably need a helper method.

A helper method is a recursive method that makes use of additional parameters to keep track of values. For recursiveSum , our helper method might look like this:

This method builds the sum by passing the working value to a new method call with the next index. When there are no more values in the array, the working sum is the actual sum.

Now we have two methods. The “starter method,” and the helper method.

The term “helper method” is actually a bit of a misnomer. It turns out that the helper method does all the work, and the other method is just a starter. It simply calls the helper method with the initial values that start the recursion.

Note that the values used in the starter call to the helper method are the same values used to initialize the local variables in the loop example. We initialize the variable used to keep track of the sum to 0.0 , and we initialize the variable used to keep track of the index to 0 .

Earlier, I said that local variables are useless in the context of recursion. This isn’t completely true, because the method parameters are indeed local variables. They work for recursion because new ones are created every time the method is called. When the recursion is executed, there are many method calls being stored in the call stack, and as a result there are many copies of the local variables.

You might ask, “If the helper method does all the work, why do we even need the starter method? Why don’t we just call the helper method with the initial values, and then you only need to write one method?”

Well, remember that we were trying to replace the method that used a for loop. That method was simple. It took an array as a parameter and returned the sum of the array as a double. If we replaced this method with one that took three parameters, we would have to remember to call it with the proper starting values. If someone else wanted to use your method, it would be impossible if he or she didn’t know the starting values.

For these reasons, it makes sense to add another method that takes care of these starting values for us.

Wrapping up

Recursion is a pretty challenging concept, but you made it all the way to the end of my explanation. I hope you understand the magic a little better. I now officially grant you the title of “Grand-Wizard of Recursion.” Congratulations!

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

20 Recursion based Practice Problems and Exercises for Beginners

@javinpaul ・ Aug 15,2022 ・ 9 min read ・ 15539 views

PAW five!

Hello guys, if you struggle to solve coding problems using recursion or have difficulty in understanding the Recusion then you are not alone. Many people struggle to understand Recursion and the only way to overcome that is solve as many Recursion coding exercises, homework, and Recursive problems as possible. This will train your brain to understand Recursion, base case, and how recursive algorithm works in genera.

you are preparing for coding interviews or trying to learn recursion but struggling and looking for recursion practice problems, recursive coding problems, or simple recursion exercises for interviews then you have come to the right place. Recursion is a simple yet difficult topic for many programmers as not everyone can understand recursion easily but it's also very important and you cannot afford to leave it alone as it's used to solve many Dynamic Programming problems like knapsack problems, Fibonacci , etc.

Solid knowledge of recursion is key to doing well in the coding interviews and that's where this article will help you. Earlier, I have shared frequently asked programming interview questions , books , and courses and here, I will share 15 Recursion practice problems and exercises you can do to learn recursion from scratch.

These are common programming questions and practice problems that can be solved using recursion, these will not only help in learning recursion but also in your coding interview preparation. I personally found the best way to learn Recursion in Java or any programming language is by doing some examples.

Every programmer knows What is a recursive function or Recursion in Java but when it comes to applying Recursion to a problem, many fumbles. As per my experience, Recursion is a tricky programming concept, few people get it very quickly, but for some programmers, it takes ages to understand Recursion and develop the ability to apply it.

If you fall into the second category of programmers for whom Recursion is always tricky, then the best I can suggest is doing lots of Recursion based programming exercises .

I know, for some people recursion is very tough to master, I was one of them but when you keep solving problems like this, from easy to difficult, you will slowly understand how recursive solution works and come up with a recursion solution for any new coding problem.

Recursion will also help you to solve dynamic programming-based coding problems, which is very important from a coding interview perspective. Recursions are also one of the most powerful techniques to solve linked lists and binary tree-based problems because both linked lists and binary trees are recursive data structures.

Since I am a Java programmer, you will Recursion based practice problems which are solved in the Java programming language but you are free to solve any programming language like C or Python or even JavaScript .

By the way, if you struggle to understand recursion patterns and recursion in general, I highly recommend going through these ** best Recursion courses for programmers to learn how to identify recursive problems and how to break them down to solve using recursion.

What is Recursion?

Just a recap of what we have discussed about Recursion in Java in our earlier article, Recursion means calling himself. A function or method is said to be Recursion if it calls itself . To write a recursion function, the first thing anyone needs is to find the base case.

The base case is a particular case that can be solved without calling a recursive function. The base case is the endpoint for the recursive function, it's the point from where the stack starts winding up. Without any base case, the recursive function will result in StackOverFlowError.

So whenever you need to write a recursive function, first write a base case. Now let's see a couple of examples of base cases in a recursive function.

If you are calculating factorial than factorial(1) = 1 is a base case, for Fibonacci numbers its f(1) and f(2), for power(int number) its power(0) which is equal to 1. See, all these base cases are conditions that can be solved without calling recursive functions.

By the way, if you like to learn from interactive courses then you can also join Recursion for Coding Interviews in Java a great interactive course from Educative to learn Recursion better, I really loved it as it also forms the basis for Dynamic Programming which they have explained in their   Grokking Dynamic Programming Patterns for Coding Interview course.

How do find if a Problem can be solved using Recursion?

Finding whether a programming problem can be solved using Recursion is a skill, not everybody sees issues in terms of Recursion.

The best thing is to break the problem into a smaller set and see if the smaller problem is the same as the original problem or not like in order to calculate a factorial of 5 , does it helps to calculate a factorial of 4? This may be a guide to see if Recursion can be used or not.

Similarly, String questions , Array-based problems , linked list algorithms , binary tree algorithms , and dynamic programming-based coding problems are good candidates for Recursion in Java.

Since a smaller linked list is a linked list, a smaller tree is a tree itself, problems like reversing the linked list, traversing the tree, etc. can be solved using Recursion in Java, and if you want to learn more, you can always join one of these best Recursion courses for beginners where I have shared both beginner and advanced level Recursion courses for coding interviews and learning Recursion from scratch.

Steps to solve a problem using Recursion

Once you have identified that a coding problem can be solved using Recursion, You are just two steps away from writing a recursive function.

1.  Find the base case 2.  Finding how to call the method and what to do with the return value.

As discussed above, finding a base case for any recursive solution is the first step toward writing a recursive function in Java or any other programming language. This is usually the simplest way to solve the problem without using recursion.

For example, when you calculate factorial, the base case is factorial(0) which is 1, you mean you know the answer so you can directly return it and from there onwards recursion will unroll and calculate factorial for the given number.

Once you have done that, you need to find a way to call the recursive method and what to do with the result returned by the method, sometime you may need to add, multiply, and divide those depending upon your problem. This will be more clear when you will solve Recursive Practice Questions in Java .

And, if you want to learn Recursion from scratch then Recursion for Coding Interviews in Java course on Educative is a great resource to start with, I really loved it as it also forms the basis for Dynamic Programming which they have explained in their   Grokking Dynamic Programming Patterns for Coding Interview course.

20 Recursion-Based Coding Problems and Exercises for Programmers

As I said the best way to learn Recursion in Java is to do examples, here are some of the programming exercises which can be solved using Recursion in Java. These recursion exercises are not too difficult and fun to solve, so try to solve them yourself before looking at answers and solutions.

  • Write a program to calculate factorial using recursion in Java. ( solution )
  • Write a program to Print Fibonacci Series in Java using Recursion. ( solution )
  • Write a program to reverse String in Java using Recursion. ( solution )
  • Write a countDown(int number) method in Java using Recursion which prints countdown till zero to console, like count(3) should print 3 2 1 0

public static void countDown(int number){ if (number == 0) { System.out.println(number); } else { System.out.println(number); countDown(number - 1); } }\

  • How to reverse Linked List using Recursion. ( solution )
  • How to print digitsToWords(int number) for example digitToWords(321) should print three or two ones? (solution)
  • Program to reverse a number using Recursion in Java?  ( solution )
  • How to calculate the sum of arithmetic series from 1 to N? (solution)
  • How to calculate the power of a number like power(int number, int power) like power(2, 3) should return 8? ( solution )
  • How to calculate Greatest Common Division  GCD using Euclid's algorithm ( solution )
  • How to print nodes of trees in the pre-order traversal using recursion? ( solution )
  • Write a Java program to convert Decimal to binary using recursion. ( solution )
  • How to code a post-order traversal algorithm using recursion? ( solution )
  • How to implement inorder traversal of binary tree using recursion? ( solution )
  • How to count the number of leaf nodes in a given binary tree? ( solution )
  • How to implement a binary search algorithm using recursion? ( solution )
  • How to find all permutations of a given String in Java? ( solution )
  • How to calculate the sum of digits using recursion in Java? ( solution )
  • How to solve the Tower of Hanoi problem using recursion?
  • How to implement bubble sort algorithms using recursion? ( solution )

That's all on these 20 Recursion Practice Problems and exercises . Once you are comfortable with these easy recursive exercises you can move on to more complex recursive exercises like the famous Tower of Hanoi problem and several other dynamic programming-based problem which requires recursive solutions.

I highly recommend you to try solving this problem by yourself, without taking help from the internet because that's the only way to learn recursion, your mind needs to be trained to understand the recursive solutions. Only see the solution if you can't solve it on your own.

Other Coding and Programing Interview Resources You may like:

  • Top 5 Free Data Structure and Algorithm Courses
  • 10 Courses to Prepare for Programming Job Interviews
  • 20+ String Algorithms Interview Questions
  • Review these Java Interview Questions for Programmers
  • Top 5 Data Structure and Algorithm Books for Java Developers
  • 20+ array-based Problems for interviews
  • 25 Software Design Interview Questions for Programmers
  • Top 30 Object-Oriented Programming Questions
  • 10 Algorithms Courses Junior Developer should join
  • 10 Algorithm Books Every Programmer Should Read
  • 7 Best Courses to learn Data Structure and Algorithms
  • Top 5 Courses to learn Dynamic Programming for Interviews

Thanks a lot for reading this article so far. If you like these recursion-based coding problems and found this article useful in learning Recursion and recursion solutions, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. -  If you need a resource to understand recursion patterns, I highly recommend going through these  best Recursion courses for programmers  to learn how to identify recursive problems and how to break them down to solve using recursion.

Share with your friends and followers

Only registered users can post comments. Please, login or signup .

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

Avatar

Blogger, Programmer, Developer

how to solve recursion problems

User Popularity

You may also like .., read devops weekly - devopslinks, read python weekly, the art and science of developing intelligent apps with openai gpt-3, dall·e 2, clip, and whisper., read ai/m weekly, read cloudnative weekly newsletter, read golang weekly, read devsecops weekly.

Join faun

Read, Learn, Know, Teach

Hand curated newsletters for Developers, private Slack with like minded people, podcasts, job offers, news and more!

Already have an account? Then please sign in .

Hey, sign up or sign in to add a reaction to my post.

Join thousands of other developers, 100% free, unsubscribe anytime.

We hate spam and we will never spam you . Already have an account? Then please sign in .

Hey there! I created FAUN to help developers learn and grow by keeping them up with what matters. Discover an effortless, straightforward way to keep up with technologies, right from your inbox and FOR FREE .

how to solve recursion problems

how to solve recursion problems

Member-only story

Python Tutorial 15 — Python Recursion: Recursive Functions and Examples

Learn how to write recursive functions, which call themselves to solve smaller problems..

Ayşe Kübra Kuyucu

Ayşe Kübra Kuyucu

Level Up Coding

Table of Contents 1. Introduction to Recursion 2. How Recursion Works in Python 3. Advantages and Disadvantages of Recursion 4. Examples of Recursive Functions in Python 5. Tips and Tricks for Writing Recursive Functions 6. Conclusion

Subscribe for FREE to get your 42 pages e-book: Data Science | The Comprehensive Handbook

Support FREE Tutorials and a Mental Health Startup.

Get step-by-step e-books on Python, ML, DL, and LLMs.

1. Introduction to Recursion

Recursion is a powerful technique in programming that allows a function to call itself repeatedly until a base case is reached. Recursion can be used to solve problems that are difficult or impossible to solve using iterative methods, such as loops.

In this tutorial, you will learn how to write recursive functions in Python, which are functions that call themselves to solve smaller problems. You will also learn the advantages and disadvantages of recursion, and see some examples of recursive functions in Python.

By the end of this tutorial, you will be able to:

  • Understand the concept of recursion and how it works in Python
  • Write your own recursive functions to solve various problems
  • Identify the benefits and drawbacks of using recursion
  • Apply recursion to different domains, such as mathematics, data structures, and algorithms

Are you ready to dive into recursion? Let’s get started!

2. How Recursion Works in Python

In this section, you will learn how recursion works in Python and what are the key components of a recursive function. You will also learn how to trace the execution of a recursive function and how to avoid common errors and pitfalls.

A recursive function is a function that calls itself within its own body. The idea behind recursion is to break down a complex problem into smaller and simpler subproblems that can be solved by the same function. For example, if you want to calculate the factorial of a number n, you can use the following formula:

However, you can also notice that the factorial of n is equal to n times the factorial of n-1, which is equal to n times n-1 times the factorial of n-2, and so on. This means that you can use recursion to define the factorial function as follows:

As you can see, the recursive function has two main components: a base case and a recursive case. The base case is the simplest case that can be solved directly without recursion. The recursive case is the case that calls the function again with a smaller or simpler argument. The recursive case must eventually lead to the base case, otherwise the recursion will never end and cause an infinite loop.

To understand how a recursive function works, you can trace its execution by following the sequence of function calls and returns. For example, if you call factorial(3), the execution will look like this:

As you can see, the function calls itself until it reaches the base case, then it returns the value of the base case and multiplies it by the previous arguments until it reaches the original argument. The final result is 6, which is the correct value of 3!.

Recursion can be a powerful and elegant way to solve problems, but it also has some drawbacks and limitations. One of the main drawbacks is that recursion can consume a lot of memory and time, as each function call creates a new stack frame that stores the local variables and parameters of the function. If the recursion is too deep or too long, it can cause a stack overflow error, which means that the program runs out of memory and crashes. Another drawback is that recursion can be hard to debug and understand, as the function calls can be nested and complex. Therefore, it is important to use recursion wisely and carefully, and to test and verify your recursive functions thoroughly.

3. Advantages and Disadvantages of Recursion

In this section, you will learn the advantages and disadvantages of using recursion in Python programming. You will also learn when to use recursion and when to avoid it, and how to compare recursion with other methods of problem-solving.

Recursion has some advantages over iterative methods, such as loops. Some of the advantages are:

  • Recursion can make the code simpler and cleaner, as it can reduce the number of lines of code and avoid unnecessary variables and loops.
  • Recursion can express the natural structure of some problems, such as tree traversal, backtracking, and divide and conquer algorithms.
  • Recursion can handle dynamic data structures, such as linked lists, graphs, and trees, more easily and efficiently than loops.

However, recursion also has some disadvantages and limitations that you should be aware of. Some of the disadvantages are:

  • Recursion can consume a lot of memory and time, as each recursive call creates a new stack frame that stores the local variables and parameters of the function. This can cause a stack overflow error if the recursion is too deep or too long.
  • Recursion can be hard to debug and understand, as the function calls can be nested and complex. It can also be difficult to trace the execution and the return values of the recursive function.
  • Recursion can sometimes be less efficient and more redundant than loops, as it can perform the same calculations or operations multiple times.

Therefore, you should use recursion wisely and carefully, and only when it is appropriate and necessary. You should also compare recursion with other methods of problem-solving, such as loops, and choose the one that suits your problem best. Some of the factors that you should consider when choosing between recursion and loops are:

  • The complexity and readability of the code. Recursion can make the code simpler and cleaner, but it can also make it harder to understand and debug.
  • The memory and time consumption of the program. Recursion can consume more memory and time than loops, but it can also handle dynamic data structures more efficiently.
  • The nature and structure of the problem. Recursion can express some problems more naturally and elegantly than loops, but it can also be unnecessary and redundant for some problems.

In summary, recursion is a powerful technique that can help you solve complex problems in Python programming, but it also has some drawbacks and limitations that you should be aware of. You should use recursion when it makes sense and when it improves your code, but you should also avoid recursion when it causes problems or when it is not needed.

4. Examples of Recursive Functions in Python

In this section, you will see some examples of recursive functions in Python that solve different types of problems. You will also learn how to write and test your own recursive functions using Python.

One of the most common examples of recursion is the Fibonacci sequence, which is a series of numbers where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci sequence are 1 and 1, and the sequence continues as follows:

You can write a recursive function to calculate the nth term of the Fibonacci sequence as follows:

To test your function, you can use the print statement to display the first 10 terms of the Fibonacci sequence:

Another example of recursion is the binary search algorithm, which is a fast and efficient way to find an element in a sorted list. The idea behind binary search is to divide the list into two halves and compare the middle element with the target element. If the middle element is equal to the target element, then the search is successful. If the middle element is greater than the target element, then the search continues in the left half of the list. If the middle element is less than the target element, then the search continues in the right half of the list. This process is repeated until the target element is found or the list is exhausted.

You can write a recursive function to implement the binary search algorithm as follows:

To test your function, you can use the following sorted list and target element:

As you can see, the function returns the index of the target element in the list, which is 6. If the target element is not in the list, the function returns -1.

These are just some examples of recursive functions in Python that solve different types of problems. You can write your own recursive functions to solve other problems, such as finding the greatest common divisor, reversing a string, or traversing a tree. The key is to identify the base case and the recursive case, and to make sure that the recursion terminates and returns a value.

5. Tips and Tricks for Writing Recursive Functions

In this section, you will learn some tips and tricks for writing recursive functions in Python. You will also learn how to avoid some common errors and pitfalls that can occur when using recursion.

Here are some tips and tricks for writing recursive functions:

  • Always define a base case and a recursive case. The base case is the simplest case that can be solved directly without recursion. The recursive case is the case that calls the function again with a smaller or simpler argument. The recursive case must eventually lead to the base case, otherwise the recursion will never end and cause an infinite loop.
  • Always return a value from the recursive function. The return value can be used to calculate the final result or to pass information to the next recursive call. If the function does not return a value, it will return None by default, which can cause unexpected errors or incorrect results.
  • Always test and verify your recursive function. You can use print statements, comments, or debugging tools to trace the execution and the return values of the recursive function. You can also use unit tests, assertions, or exceptions to check the validity and correctness of the function.
  • Always consider the trade-offs between recursion and iteration. Recursion can make the code simpler and cleaner, but it can also consume more memory and time than iteration. Recursion can express some problems more naturally and elegantly, but it can also be unnecessary and redundant for some problems. You should compare recursion with iteration and choose the one that suits your problem best.

Here are some common errors and pitfalls that can occur when using recursion:

  • Stack overflow error. This error occurs when the recursion is too deep or too long, and the program runs out of memory and crashes. To avoid this error, you should limit the depth or the length of the recursion, or use a different method of problem-solving.
  • Logic error. This error occurs when the recursive function does not produce the correct result or does not terminate. To avoid this error, you should make sure that the base case and the recursive case are defined correctly, and that the recursion converges to the base case.
  • Redundancy error. This error occurs when the recursive function performs the same calculations or operations multiple times, which can reduce the efficiency and increase the complexity of the program. To avoid this error, you should use memoization or dynamic programming techniques to store and reuse the results of previous recursive calls.

These are some tips and tricks for writing recursive functions in Python. You can use these tips and tricks to improve your skills and confidence in using recursion, and to solve complex problems in Python programming.

6. Conclusion

In this tutorial, you have learned how to write recursive functions in Python, which are functions that call themselves to solve smaller problems. You have also learned the advantages and disadvantages of recursion, and seen some examples of recursive functions in Python.

Recursion is a powerful technique that can help you solve complex problems in Python programming, but it also has some drawbacks and limitations that you should be aware of. You should use recursion wisely and carefully, and only when it is appropriate and necessary. You should also compare recursion with other methods of problem-solving, such as loops, and choose the one that suits your problem best.

We hope that this tutorial has been useful and informative for you, and that you have enjoyed learning about recursion in Python. If you want to learn more about Python programming, you can check out some of the following resources:

  • [Python Documentation]: The official documentation of the Python language, where you can find tutorials, references, and guides on various topics.
  • [Python for Beginners]: A website that provides free and interactive Python tutorials for beginners, covering the basics of the language, data structures, functions, modules, and more.
  • [Real Python]: A website that offers high-quality Python tutorials, articles, courses, and books for all levels of Python learners, covering a wide range of topics and applications.

Thank you for reading this tutorial, and happy coding!

The complete tutorial list is here:

Python Tutorial Series: 50 Step-by-Step Lessons [FREE][2024]

Updated weekly — 06.12.2023.

Ayşe Kübra Kuyucu

Written by Ayşe Kübra Kuyucu

AI-Based Tutorials | linkedin.com/in/aysekubrakuyucu | Free ebook: aysekubrakuyucu.substack.com/subscribe | Donate: https://donate.stripe.com/6oE29U41X1kx0F2aEE

More from Ayşe Kübra Kuyucu and Level Up Coding

Python Tutorial 13 — Python Functions: Defining and Calling Functions

Python Tutorial 13 — Python Functions: Defining and Calling Functions

Learn how to define and call functions, which are reusable blocks of code..

Jacob Bennett

Jacob Bennett

The 5 paid subscriptions I actually use in 2024 as a software engineer

Tools i use that are cheaper than netflix.

API Design 101: From Basics to Best Practices

Hayk Simonyan

API Design 101: From Basics to Best Practices

Api design, from the basics to best practices..

Python Tutorial 20 — Python Classes and Objects: Creation and Usage

Python in Plain English

Python Tutorial 20 — Python Classes and Objects: Creation and Usage

Learn how to create and use classes and objects in python oop., recommended from medium.

Why Python’s Duck Typing is the Quackiest Thing You’ll Ever Love

Builescu Daniel

Why Python’s Duck Typing is the Quackiest Thing You’ll Ever Love

Dive into the charm of python’s duck typing, where code flexibility meets creativity. a whimsical journey awaits.

JS Toolbox 2024 Part 3: Bundlers and test frameworks

JS Toolbox 2024 Part 3: Bundlers and test frameworks

Javascript is bigger than ever, and the ecosystem is nothing short of overwhelming. in this js toolbox 2024 series, we’ve selected and….

how to solve recursion problems

General Coding Knowledge

how to solve recursion problems

Coding & Development

how to solve recursion problems

Stories to Help You Grow as a Software Developer

how to solve recursion problems

Predictive Modeling w/ Python

Recursion in Python Demystified

Marcin Kozak

Towards Data Science

Recursion in Python Demystified

The article shows simple examples of flat and nested recursion patterns in python..

The Magic of Decorators: Unleash Your Creativity in Python

The Magic of Decorators: Unleash Your Creativity in Python

Decorator is a special tool in python that provides us with the flexibility to modify functions from outside. it’s like a magical hat with….

Awesome Worker Distribution With Toolips 0.3

Emma Boudreau

Awesome Worker Distribution With Toolips 0.3

A brief overview of the new distributed computing system in toolips.jl..

Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks

Jason Roell

Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks

This cheat sheet was born out of necessity. recently, i was tasked with diving into a new python project after some time away from the….

Text to speech

AP CS Recursive Tracing Lesson

Note: this lesson is a work in progress. We are working to add more content—but you might find what we have so far useful.

  • Recursive Tracing Tutorial (10 mins) This video covers how to simulate the execution of a recursive Java method.
  • The conceptual basis behind recursion;
  • The similarities and differences between recursion and iteration..
  • Java Recursive Tracing Slides (PDF)
  • Java Recursive Tracing (Powerpoint)

Practice-it problems

Here's a list of recursive tracing "mystery" problems on Practice-it. These problems allow students to practice tracing the execution of a recursive method.

  • Recursion Tracing mystery1
  • Recursion Tracing mystery2
  • Recursion Tracing mystery3
  • Recursion Tracing mystery4
  • Recursion Tracing mystery5
  • Recursion Tracing mystery6
  • Recursion Tracing mystery7
  • Recursion Tracing mystery8
  • Recursion Tracing mystery9

Learn How to Think Recursively? Solving Problems Using Recursion

Disclaimer: This post may contain affiliate links, meaning will make a commission if you buy something via my links, at no extra cost to you. Read my disclosure for more info.

recursion

Recursion means that “ defining a haul in terms of itself “. In this post, you’ll learn to think recursively, and it could be a really powerful tool in writing algorithms.

The formula comes directly from Mathematics, wherever there are several samples of expressions written in terms of themselves

Best Courses to Learn Data Structures and Algorithm for cracking tech interview

Recursion is one most helpful method which might be utilized in rule design. So, understanding how recursion behaves in computer programs is obligatory for all computer engineers.

The formula isn’t hard, whereas thinking algorithmically may well be confusing in some cases.

The recursive algorithm has good blessings over identical unvarying algorithms corresponding to having fewer code lines and reduced use of information structures.

But, well-known drawbacks of recursion are high memory usage and the slow period since it uses a call stack.

Furthermore, every recursive resolution can be regenerate into even iterative solution victimization of the stack data structure, and vice versa.

How to Solve Recursion Problem?

Recursion is somewhat nuanced and very much depends on what downside you’re attempting to solve. However, there are some general steps we can return up thereupon can additional or less lead us in the right direction. Start your coding journey with Python, here’s how .

How to Think Recursively?

Here’s the recursion function for finding factorial of 7 using recursion. A big problem finds another subproblem and continues till it returns. Then the prior function gets the values of the caller function subsequently.

Recursive Function

3 steps for recursion:

Order Your Data

  • Solve little Cases 
  • Solve Big Cases

This step is completely the key to obtaining beginner in determination a drag recursively, and nonetheless, it’s often unmarked or performed implicitly.

Whether or not it is numbers, strings, lists, binary trees, or people, it is necessary to expressly notice an acceptable ordering that provides us a direction to maneuverer in to form the matter smaller.

This ordering depends entirely on the problem, however, an honest start is to consider the apparent orderings.

Numbers go together with their ordering, strings and lists are often ordered by their length, binary trees can be ordered by depth.

And other people are often ordered in an infinite range of smart ways. For example, height, weight or rank in an organization.

Once we’ve ordered our data, we can think of it as something that we can reduce. We can write out our ordering as a sequence:

0 ,  1 ,  2 , …,  n  for integers

Solve Little Cases 

This can be the unremarkably easiest part. Once we’ve got the proper ordering, we’d like to see at smallest components in our ordering and choose how we are progressing to handle them.

Once we have solved our base cases, and that we grasp our ordering, then finding the final case is simple.

Solve the Massive Case

Here, we tend to handle the information rightwards in our ordering, that is, data of a high degree.

Usually, we take into account data of arbitrary degree and aim to seek out how to unravel the matter by reducing it to an expression containing a similar problem of a lesser degree.

For example, in our Fibonacci example, we started with arbitrary  n  and reduced:

fib(n) to fib(n-1) + fib(n-2)  that is an expression containing 2 instances of the problem we started with, of

lesser degree  (n-1 and n-2, respectively).

There is often over one algorithmic case that we must think about as information of a given data type will take slightly different forms. However, it can entirely depend on drawback.

Memory for the function is divided into two parts one for stacking functional calls and other for memory heap that stores data to be referred and used by functions.

Stack and Heap In RAM

The call stack create a block for data and computation for each function that are not get returned and are arranged on top of each other and returned using FIFO principle

Recurive function execution

Should You Avoid Recursion?

There aren’t any definitive rules for once to and when to not use rule.

There are some times when recursion is necessary, and at different times, you have got to use your “programming instincts” to choose whether or not or not to solve recursively.

I know it may be frustrating, however like most style selections there’s no laborious rule.

The rule ought to be used once it is sensible to try and do so, and we avoid when it will not.

Any toughened engineer can acknowledge an algorithmic design immediately and have enough expertise to understand/debug it.

As a beginner, I will solely advocate that you simply experiment with each solution till you get compassionate when one is healthier than the other.

Recursion uses a lot of memory however is typically clearer and more readable. victimization loops will increase the performance, but the formula will sometimes be higher for the technologist.

Recursion in Python

When you call a function in Python, the interpreter creates a brand-new native namespace so names outlined among that function don’t impinge on identical names defined elsewhere. How to learn Python at an employable level?

One function will call another, and even though they each define objects with identical names, it all works out fine as a result of those objects exist in separate namespaces.

About The Author

how to solve recursion problems

Mahak Bafna

Leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Start typing and press enter to search

IMAGES

  1. 5 Simple Steps for Solving Any Recursive Problem

    how to solve recursion problems

  2. How to solve recursive sequences in Math, practice problems explained

    how to solve recursion problems

  3. How to solve recursive sequences in Math, practice problems explained

    how to solve recursion problems

  4. Learn How to Think Recursively? Solving Problems Using Recursion

    how to solve recursion problems

  5. How to use Recursive Formulas?: Algebra

    how to solve recursion problems

  6. How to solve recursive sequences in Math, practice problems explained

    how to solve recursion problems

VIDEO

  1. Extra Problems 2 Recursion Recursion Inside Recursion

  2. Recursion Problems

  3. What is Recursion ?

  4. Recursion Algorithms In 5 Minutes How to solve Recursion Problem Recursion Data Structure #shorts

  5. C++ Recursion Problems [12-1-24] DSA with C++ by 4ByteInteger

  6. Recursion in C Programming

COMMENTS

  1. How to Think Recursively

    Step 1) Know what your function should do The first step to solve recursion problems, is to know what your function is suppose to do. Reader: Do you think I'm an idiot? This might seem obvious, but it's an important step that gets glossed over. You need to think about what your function should do, not what it currently does.

  2. Recursive Practice Problems with Solutions

    Practice Basics - Recursion Recursive Functions Tail Recursion Strings - Given a string, print all possible palindromic partitions Check if a number is Palindrome Print all possible strings of length k that can be formed from a set of n characters Recursive Implementation of atoi ()

  3. Recursion (article)

    Course: Computer science theory > Unit 1 Lesson 6: Recursive algorithms Computing > Computer science theory > Algorithms > Recursive algorithms Recursion Google Classroom Have you ever seen a set of Russian dolls? At first, you see just one figurine, usually painted wood, that looks something like this:

  4. Train Your Mind to Think Recursively in 5 Steps

    How to solve recursive problems easily? Sara A. Metwalli · Follow Published in Towards Data Science · 6 min read · Oct 31, 2020 -- 5 Photo by Reid Zura on Unsplash Along the way on your programming journey, there are a few milestones that you need to conquer to advance ahead.

  5. 5 Simple Steps for Solving Any Recursive Problem

    0:00 / 21:02 5 Simple Steps for Solving Any Recursive Problem Reducible 270K subscribers Subscribe Subscribed 36K Share Save 1.1M views 4 years ago In this video, we take a look at one of the...

  6. Recursion

    Recursion should be applied as a technique when the problem you're solving is like an onion. Using recursion requires realizing that a big, complex problem that's likely to make you cry is really just a slightly smaller problem, plus one super-thin layer. And that problem, in turn, is just a slightly smaller problem, plus one super-thin layer...

  7. What Is Recursion in Programming, and How Do You Use It?

    The long answer is that recursion can help solve complicated problems by breaking them down into smaller subsets of the main problem. Often, you will have data structures containing nested data. Breaking this down into smaller amounts of data will make this easier to process.

  8. Introduction to Recursion

    Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A recursive function solves a particular problem by calling a copy of itself and solving smaller subproblems of the original problems.

  9. PDF Lecture 15: Recursive Algorithms

    • Design your own recursive algorithm - Constant-sized program to solve arbitrary input - Need looping or recursion, analyze by induction - Recursive function call: vertex in a graph, directed edge from A → B if B calls A - Dependency graph of recursive calls must be acyclic (if can terminate) - Classify based on shape of graph

  10. Recursion 101. Solve problems recursively by taking it…

    Solve problems recursively by taking it one step at a time Adam Snyder · Follow Published in Better Programming · 10 min read · Nov 6, 2019 -- Photo by Tine Ivanič on Unsplash Welcome to Recursion 101. By the end of this piece, you will have a deeper understanding of solving problems recursively and also of a relating data structure.

  11. A Guide To Recursion With Examples

    A recursive solution to a problem must have two steps: the base case (the smallest problem to solve) and the recursive steps (applying the same solution over and over till we reach the base case). Iteration can be used instead of recursion. Yet, recursive solutions can be simpler for specific types of problem, like tree-shaped data structure or ...

  12. Recursive Programming. How to solve a problem by pretending…

    In fact, every problem we can solve using recursion, we can also solve using iteration ( for and while loops). So why would we ever choose to use recursion? Me writing this post recursively Why recursion? Believe it or not, once we get to grips with it, some problems are easier to solve using recursion than they are to solve using iteration.

  13. Recursion Explained: What is Recursion in Programming?

    Finding the nth Factorial: n! = n * (n - 1)! Recursion means solving the problem using the solution of smaller sub-problems. This blog will explain these critical concepts: 1) What is recursion? 1) How recursion works in programming? 2) Advantages and disadvantages of recursion 3) Steps to solve problems using recursion?

  14. Recursion Practice Problems with Solutions

    Recursion is a problem-solving technique that involves breaking a problem into smaller and simpler problems of the same kind (also called subproblems) until we get a small enough subproblem having a trivial solution. We can say that recursion is "defining a problem in terms of itself" as it involves a function calling itself with a base ...

  15. How to Solve Recursive Sequences

    How to Solve Recursive Sequences Table of contents top Visualization Examples 2 phases Practice Recursion What is a Recursive Sequence? A Recursive Sequence is a function that refers back to itself. Below are several examples of recursive sequences.

  16. How to build up an intuition for recursion

    I want to help you build an intuition for recursion so you can use it to solve problems. I am a teaching assistant for the introductory computer science course at my university. I've explained recursion in exactly the same way a dozen times this week. My explanation seems to help most students. This article has the most general explanation at ...

  17. How should you approach recursion?

    11 I am currently studying recursion in school, and I have trouble thinking about methods when there are many recursive calls. I just want to ask how you should think about recursion because I know tracing the method calls by each step will become too tedious.

  18. 20 Recursion based Practice Problems and Exercises for Beginners

    Many people struggle to understand Recursion and the only way to overcome that is solve as many Recursion coding exercises, homework, and Recursive problems as possible. This will train your brain to understand Recursion, base case, and how recursive algorithm works in genera.

  19. Real-world examples of recursion

    Recursion is appropriate whenever a problem can be solved by dividing it into sub-problems, that can use the same algorithm for solving them. Algorithms on trees and sorted lists are a natural fit. Many problems in computational geometry (and 3D games) can be solved recursively using binary space partitioning (BSP) trees, fat subdivisions , or ...

  20. Python Tutorial 15

    You can write your own recursive functions to solve other problems, such as finding the greatest common divisor, reversing a string, or traversing a tree. The key is to identify the base case and the recursive case, and to make sure that the recursion terminates and returns a value. 5. Tips and Tricks for Writing Recursive Functions

  21. Recursion in Python Demystified. The article shows simple examples of

    In flat recursion, a function calls itself, but the subsequent calls do not call the same function again. Since each call of the function leads to a single subsequent call, there's no nesting of function calls within each other; In nested recursion, a function calls itself, and the subsequent calls may also call the same function again. This ...

  22. AP CS Recursive Tracing Lesson

    How to write a recursive method to solve a problem; The similarities and differences between recursion and iteration.. Note that the AP test does not ask students to write recursive methods, so this lecture might be overkill to show to students. ... Here's a list of recursive tracing "mystery" problems on Practice-it. These problems allow ...

  23. Learn How to Think Recursively? Solving Problems Using Recursion

    Here's the recursion function for finding factorial of 7 using recursion. A big problem finds another subproblem and continues till it returns. Then the prior function gets the values of the caller function subsequently. 3 steps for recursion: Order Your Data; Solve little Cases ; Solve Big Cases; Order Your Data

  24. How to solve any recursion problem !!!! Master of solving ...

    To solve a recursion problem, let's ASSUME that the function already works for any subproblem we want. Because of our subproblem selection, we already have the sum of all values from 1 to n-1 ...

  25. Eldan on Instagram: "Save it! next 5 out of 14 Patterns to ace any

    37 likes, 2 comments - eldan.nomad on February 4, 2024: "Save it! next 5 out of 14 Patterns to ace any coding interview. . . 6. In-place reversal of link..."