Data Structure Recursion Practice Questions with Solutions

Introductions

Recursion is a problem-solving technique where a function calls itself to solve a smaller version of the same problem. In data structures and algorithms, recursion is commonly used for calculations, searching, tree traversal, divide-and-conquer problems, and backtracking. These practice questions focus on understanding recursion through simple coding problems and gradually introduce concepts such as base cases, recursive calls, arrays, strings, and recursive problem solving. Data Structure Recursion practice questions with solutions help to understand the concepts.

Question 1: Print Numbers from 1 to N Using Recursion

Question

Write a recursive function to print numbers from 1 to 5.

Solution

A recursive function needs two important parts:

  • Base case — tells the function when to stop.
  • Recursive call — calls the same function with a smaller or changed value.

For this problem, we can print the number after making the recursive call.

function printNumbers(n) {
    if (n === 0) {
        return;
    }

    printNumbers(n - 1);
    console.log(n);
}

printNumbers(5);

Let’s understand the calls:

printNumbers(5)
    ↓
printNumbers(4)
    ↓
printNumbers(3)
    ↓
printNumbers(2)
    ↓
printNumbers(1)
    ↓
printNumbers(0)

At 0, the function stops.

Then the numbers are printed while the recursive calls return.

Output

1
2
3
4
5

Answer

The function prints numbers from 1 to 5 using recursion.


Question 2: Find the Factorial of a Number Using Recursion

Question

Find the factorial of 5 using recursion.

Recall:

5! = 5 × 4 × 3 × 2 × 1

Solution

The factorial can be written recursively as:

n! = n × (n - 1)!

The base case is:

0! = 1

JavaScript code:

function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    }

    return n * factorial(n - 1);
}

console.log(factorial(5));

The recursive calculation is:

factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1

Therefore:

5! = 120

Output

120

Answer

The factorial of 5 is 120.


Question 3: Find the Sum of Numbers from 1 to N

Question

Find the sum of numbers from 1 to 5 using recursion.

Expected calculation:

1 + 2 + 3 + 4 + 5

Solution

We can define the problem as:

sum(n) = n + sum(n - 1)

The base case is:

sum(0) = 0

Code:

function sumNumbers(n) {
    if (n === 0) {
        return 0;
    }

    return n + sumNumbers(n - 1);
}

console.log(sumNumbers(5));

Step by step:

sumNumbers(5)
= 5 + sumNumbers(4)
= 5 + 4 + sumNumbers(3)
= 5 + 4 + 3 + sumNumbers(2)
= 5 + 4 + 3 + 2 + sumNumbers(1)
= 5 + 4 + 3 + 2 + 1 + sumNumbers(0)

Since:

sumNumbers(0) = 0

The final result is:

5 + 4 + 3 + 2 + 1 = 15

Output

15

Answer

The sum of numbers from 1 to 5 is 15.


Question 4: Find the Sum of Array Elements Using Recursion

Question

Find the sum of all elements in this array using recursion:

[10, 20, 30, 40]

Solution

Instead of using a loop, we can recursively process one array element at a time.

function arraySum(arr, index) {
    if (index === arr.length) {
        return 0;
    }

    return arr[index] + arraySum(arr, index + 1);
}

let numbers = [10, 20, 30, 40];

console.log(arraySum(numbers, 0));

The recursive process is:

10 + arraySum(1)
20 + arraySum(2)
30 + arraySum(3)
40 + arraySum(4)

When index becomes 4, it reaches the end of the array.

So:

10 + 20 + 30 + 40 = 100

Output

100

Answer

The sum of all array elements is 100.


Question 5: Find the Maximum Element in an Array Using Recursion

Question

Find the largest element in:

[12, 45, 23, 67, 34]

using recursion.

Solution

We can recursively compare the current element with the maximum value found in the remaining part of the array.

function findMax(arr, index) {
    if (index === arr.length - 1) {
        return arr[index];
    }

    let maxOfRest = findMax(arr, index + 1);

    return Math.max(arr[index], maxOfRest);
}

let numbers = [12, 45, 23, 67, 34];

console.log(findMax(numbers, 0));

The function eventually compares:

34
67
23
45
12

The largest value is 67.

Output

67

Answer

The maximum element in the array is 67.


Question 6: Reverse a String Using Recursion

Question

Reverse the string:

"hello"

using recursion.

Expected result:

"olleh"

Solution

Take the first character and recursively reverse the remaining string.

function reverseString(str) {
    if (str.length <= 1) {
        return str;
    }

    return reverseString(str.slice(1)) + str[0];
}

console.log(reverseString("hello"));

Let’s understand the recursive calls:

reverseString("hello")
reverseString("ello")
reverseString("llo")
reverseString("lo")
reverseString("o")

The base case is reached when only one character remains.

Then the characters are added back in reverse order.

o
ol
oll
olle
olleh

Output

olleh

Answer

The reversed string is “olleh”.


Question 7: Check Whether a String is a Palindrome

Question

Check whether the following string is a palindrome using recursion:

"madam"

A palindrome reads the same from both directions.

Solution

We compare the first and last characters.

For "madam":

m == m

Then check the smaller string:

"ada"

Again:

a == a

Then:

"d"

A single character is a palindrome.

Code:

function isPalindrome(str, start, end) {
    if (start >= end) {
        return true;
    }

    if (str[start] !== str[end]) {
        return false;
    }

    return isPalindrome(str, start + 1, end - 1);
}

let word = "madam";

console.log(
    isPalindrome(word, 0, word.length - 1)
);

The comparisons are:

m == m
a == a
d == d

No characters are different.

Output

true

Answer

"madam" is a palindrome.


Question 8: Calculate the Power of a Number Using Recursion

Question

Calculate:

2⁵

using recursion.

Solution

The recursive formula is:

base^power = base × base^(power - 1)

The base case is:

base^0 = 1

Code:

function power(base, exponent) {
    if (exponent === 0) {
        return 1;
    }

    return base * power(base, exponent - 1);
}

console.log(power(2, 5));

The calculation becomes:

2 × power(2, 4)
2 × 2 × power(2, 3)
2 × 2 × 2 × power(2, 2)
2 × 2 × 2 × 2 × power(2, 1)
2 × 2 × 2 × 2 × 2 × power(2, 0)

Since:

power(2, 0) = 1

The result is:

2 × 2 × 2 × 2 × 2 = 32

Output

32

Answer

2⁵ is 32.


Question 9: Find the Fibonacci Number Using Recursion

Question

Find the 6th Fibonacci number using recursion.

Use this sequence:

0, 1, 1, 2, 3, 5, 8...

Solution

Each Fibonacci number is calculated using the previous two numbers:

F(n) = F(n - 1) + F(n - 2)

The base cases are:

F(0) = 0
F(1) = 1

Code:

function fibonacci(n) {
    if (n === 0) {
        return 0;
    }

    if (n === 1) {
        return 1;
    }

    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6));

The sequence is:

F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8

Output

8

Answer

The 6th Fibonacci number is 8.


Question 10: Perform Binary Search Using Recursion

Question

Use recursive binary search to find 40 in the sorted array:

[10, 20, 30, 40, 50, 60, 70]

Solution

Binary search works by repeatedly dividing the search range into two parts.

First, calculate the middle index:

middle = Math.floor((left + right) / 2)

If the middle value is smaller than the target, search the right half.

If the middle value is greater than the target, search the left half.

Code:

function binarySearch(arr, target, left, right) {

    if (left > right) {
        return -1;
    }

    let middle = Math.floor((left + right) / 2);

    if (arr[middle] === target) {
        return middle;
    }

    if (target < arr[middle]) {
        return binarySearch(arr, target, left, middle - 1);
    }

    return binarySearch(arr, target, middle + 1, right);
}

let numbers = [10, 20, 30, 40, 50, 60, 70];

let result = binarySearch(
    numbers,
    40,
    0,
    numbers.length - 1
);

console.log("Index:", result);

Let’s follow the search.

First:

left = 0
right = 6
middle = 3

At index 3:

arr[3] = 40

The target is found immediately.

Output

Index: 3

Answer

The value 40 is found at index 3.

Binary search takes O(log n) time on a sorted array.

Key Takeaways

  • Recursion means a function calls itself to solve a smaller version of a problem.
  • Every recursive solution needs a base case to stop the recursion.
  • A recursive case moves the problem toward the base case.
  • Factorial and Fibonacci are common examples of recursive problems.
  • Arrays can be processed recursively by changing the index during each call.
  • Strings can be reversed and checked for palindromes using recursion.
  • Recursion can be used with searching algorithms such as binary search.
  • Recursive solutions often use the call stack to remember previous function calls.
  • If a recursive function never reaches its base case, it can cause excessive recursion and eventually a stack overflow.
  • Binary search using recursion has O(log n) time complexity.
  • Simple recursive array or string traversal generally takes O(n) time.
  • The space used by recursion depends on the number of active recursive calls on the call stack.
  • Recursion is especially useful for problems that naturally break into smaller versions of the same problem.

FAQs

1. What is recursion in data structures?

Recursion is a technique where a function calls itself to solve a smaller version of the same problem until a base condition is reached.

2. Why is a base case important in recursion?

The base case tells the recursive function when to stop. Without a proper base case, the function may continue calling itself and cause a stack overflow.

3. What is a recursive call?

A recursive call is a function call made by the function to itself, usually with a smaller or modified input.

4. What happens when a recursive function reaches its base case?

The recursive calls stop, and the previous calls begin returning their results back through the call stack.

5. Can arrays be processed using recursion?

Yes. An array can be processed recursively by using an index and moving that index toward the end of the array.

6. Is recursion always better than a loop?

No. Recursion can make some problems easier to understand, but it can also use additional call-stack memory. For simple repetitive tasks, a loop may be more efficient.

7. What is the difference between recursion and iteration?

Recursion uses repeated function calls, while iteration uses loops such as for and while. Both can solve many of the same problems, but recursion is particularly useful when a problem naturally breaks into smaller similar problems.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top