Skip to content

Commit 0145bf6

Browse files
authored
Merge pull request #1005 from MuraliDharan7/add-recursion-doc
Added Recursion doc in beginner module
2 parents 8fd89a7 + f508f9b commit 0145bf6

File tree

1 file changed

+202
-0
lines changed

1 file changed

+202
-0
lines changed

dsa/beginner/002-Recursion.md

+202
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
---
2+
id: 0002-recursion
3+
title: Recursion
4+
sidebar_label: Recursion
5+
tags:
6+
- Basics
7+
- Algorithms
8+
- DSA
9+
- Python
10+
- C++
11+
- Java
12+
- JavaScript
13+
description: "This page explains the concept of Recursion with detailed explanations, examples, and code implementations."
14+
---
15+
16+
## 1. What is Recursion?
17+
18+
Recursion is a programming technique where a function calls itself in order to solve a problem. This technique divides the problem into smaller, more manageable sub-problems. A recursive function has two main parts:
19+
- **Base Case:** The condition under which the function stops calling itself.
20+
- **Recursive Case:** The part where the function calls itself with a smaller or simpler sub-problem.
21+
22+
## 2. How Does Recursion Work?
23+
24+
Recursion works by breaking down a problem into smaller instances of the same problem until a base case is reached. The base case is the simplest form of the problem, which can be solved directly without further recursion. Once the base case is reached, the function returns a value, and the recursive calls start to resolve in reverse order, ultimately solving the entire problem.
25+
26+
### Example: Factorial of a Number
27+
28+
The factorial of a number `n` (denoted as `n!`) is the product of all positive integers less than or equal to `n`.
29+
30+
- **Factorial of 5:** `5! = 5 * 4 * 3 * 2 * 1 = 120`
31+
32+
Here is the recursive definition of factorial:
33+
- **Base Case:** `0! = 1`
34+
- **Recursive Case:** `n! = n * (n - 1)!`
35+
36+
## Algorithmic Approach
37+
38+
#### The algorithmic steps for implementing recursion in a function are as follows:
39+
40+
- Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself.
41+
42+
- Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem.
43+
44+
- Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop.
45+
46+
- Step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original problem.
47+
48+
## How are recursive functions stored in memory?
49+
50+
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. ![Recursive memore](https://www.geeksforgeeks.org/stack-data-structure/)
51+
52+
### What is the base condition in recursion?
53+
- 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.
54+
55+
```
56+
int fact(int n)
57+
{
58+
if (n < = 1) // base case
59+
return 1;
60+
else
61+
return n*fact(n-1);
62+
}
63+
```
64+
65+
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.
66+
67+
### Why Stack Overflow error occurs in recursion?
68+
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.
69+
70+
```
71+
int fact(int n)
72+
{
73+
// wrong base case (it may cause
74+
// stack overflow).
75+
if (n == 100)
76+
return 1;
77+
78+
else
79+
return n*fact(n-1);
80+
}
81+
```
82+
83+
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.
84+
85+
## 3. Problem Description
86+
87+
Compute the factorial of a given number using recursion.
88+
89+
## 4. Examples
90+
91+
### Example 1:
92+
**Input:** `n = 5`
93+
**Output:** `120`
94+
95+
### Example 2:
96+
**Input:** `n = 0`
97+
**Output:** `1`
98+
99+
## 5. Constraints
100+
101+
- $0 \leq n \leq 12$ (for reasonable output)
102+
103+
## 6. Algorithm for Recursion
104+
105+
1. Define the base case for the smallest problem.
106+
2. Define the recursive case that breaks the problem into smaller sub-problems.
107+
3. Ensure the problem size decreases with each recursive call to reach the base case.
108+
109+
## 7. Implementation (Code for 4 Languages)
110+
111+
<Tabs>
112+
<TabItem value="Python" label="Python" default>
113+
```python
114+
def factorial(n):
115+
if n == 0:
116+
return 1
117+
else:
118+
return n * factorial(n - 1)
119+
120+
# Example usage:
121+
print(factorial(5)) # Output: 120
122+
```
123+
</TabItem>
124+
125+
<TabItem value="C++" label="C++">
126+
```cpp
127+
#include <iostream>
128+
using namespace std;
129+
130+
int factorial(int n) {
131+
if (n == 0)
132+
return 1;
133+
else
134+
return n * factorial(n - 1);
135+
}
136+
137+
int main() {
138+
cout << factorial(5) << endl; // Output: 120
139+
return 0;
140+
}
141+
```
142+
</TabItem>
143+
144+
<TabItem value="Java" label="Java">
145+
```java
146+
public class Recursion {
147+
public static int factorial(int n) {
148+
if (n == 0)
149+
return 1;
150+
else
151+
return n * factorial(n - 1);
152+
}
153+
154+
public static void main(String[] args) {
155+
System.out.println(factorial(5)); // Output: 120
156+
}
157+
}
158+
```
159+
</TabItem>
160+
161+
<TabItem value="JavaScript" label="JavaScript">
162+
```javascript
163+
function factorial(n) {
164+
if (n === 0) {
165+
return 1;
166+
} else {
167+
return n * factorial(n - 1);
168+
}
169+
}
170+
171+
// Example usage:
172+
console.log(factorial(5)); // Output: 120
173+
```
174+
</TabItem>
175+
</Tabs>
176+
177+
## 8. Complexity Analysis
178+
179+
- **Time Complexity:** $O(n)$, where $n$ is the number of recursive calls.
180+
- **Space Complexity:** $O(n)$, due to the call stack.
181+
182+
## 9. Advantages and Disadvantages
183+
184+
### Advantages:
185+
- Simplifies code for problems that can be broken into similar sub-problems.
186+
- Natural fit for problems that have a recursive structure, such as tree traversals.
187+
188+
### Disadvantages:
189+
- May lead to high memory usage due to the call stack, especially for deep recursions.
190+
- Can be slower due to the overhead of multiple function calls.
191+
192+
## 10. Examples of Recursion in Practice
193+
194+
- **Fibonacci Series:** Computing Fibonacci numbers.
195+
- **Tree Traversals:** Pre-order, in-order, and post-order traversals.
196+
- **Backtracking Algorithms:** Solving puzzles like Sudoku or the N-Queens problem.
197+
- **Divide and Conquer Algorithms:** Merge sort, quicksort, etc.
198+
199+
## 11. References
200+
201+
- [GeeksforGeeks - Recursion](https://www.geeksforgeeks.org/recursion/)
202+
- [Wikipedia - Recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science))

0 commit comments

Comments
 (0)