allizwell.jobsdoor360.in

Recursion on Arrays

Data Structures and Algorithms / Recursion and Backtracking / Recursion on Arrays

Recursion on Arrays

Recursion on arrays means solving array-related problems by processing elements through recursive function calls instead of relying entirely on loops. We use an index to track the current element and move toward a base case when all required elements have been processed.

1. What Is Recursion on Arrays?

An array stores multiple elements of the same data type in contiguous memory locations. We usually access an element using its index.

In recursive array processing, a function handles the current element and then calls itself with the next index or a smaller range of the array.

Example

Consider the following array:

int arr[] = {10, 20, 30, 40, 50};

We can print all elements recursively by starting at index 0 and moving toward index 5. When the index becomes equal to the array size, recursion stops.

2. Basic Structure of Recursive Array Processing

A typical recursive array function follows this structure:

  1. Pass the array and its current index to the function.
  2. Check whether the base case has been reached.
  3. Process the current array element.
  4. Call the function again with the next index.
void processArray(int arr[], int index, int n) {

    // Base case
    if (index == n) {
        return;
    }

    // Process current element
    cout << arr[index] << " ";

    // Recursive call
    processArray(arr, index + 1, n);
}
Important: The valid indexes of an array of size N are from 0 to N - 1. Therefore, index == n is a useful stopping condition when traversing the entire array from left to right.

3. Array Traversal Using Recursion

Array traversal means visiting each element of an array one by one. We can perform this operation recursively by increasing the index after processing each element.

C++ Program

#include <iostream>
using namespace std;

void printArray(int arr[], int index, int n) {

    // Base case
    if (index == n) {
        return;
    }

    // Print current element
    cout << arr[index] << " ";

    // Move to next element
    printArray(arr, index + 1, n);
}

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;

    printArray(arr, 0, n);

    return 0;
}

Output

10 20 30 40 50

Dry Run

Function Call Current Element Next Call
printArray(arr, 0, 5) 10 Index 1
printArray(arr, 1, 5) 20 Index 2
printArray(arr, 2, 5) 30 Index 3
printArray(arr, 3, 5) 40 Index 4
printArray(arr, 4, 5) 50 Index 5
printArray(arr, 5, 5) Base case Return

4. Print an Array in Reverse Order

We can print an array in reverse order by first making the recursive call and printing the current element after that call returns.

This works because recursive calls are stored on the call stack. The print statement executes while the function calls return.

C++ Program

#include <iostream>
using namespace std;

void printReverse(int arr[], int index, int n) {

    // Base case
    if (index == n) {
        return;
    }

    // Recursive call first
    printReverse(arr, index + 1, n);

    // Print while returning
    cout << arr[index] << " ";
}

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;

    printReverse(arr, 0, n);

    return 0;
}

Output

50 40 30 20 10

Remember: Code written before the recursive call executes while going deeper into recursion. Code written after the recursive call executes while returning from recursion.

5. Find the Sum of Array Elements

We can calculate the sum of all array elements recursively. Add the current element to the result returned by the recursive call for the remaining elements.

For example:

Array: {2, 4, 6, 8}

Sum = 2 + 4 + 6 + 8 = 20

C++ Program

#include <iostream>
using namespace std;

int arraySum(int arr[], int index, int n) {

    // Base case
    if (index == n) {
        return 0;
    }

    // Current element + remaining sum
    return arr[index] + arraySum(arr, index + 1, n);
}

int main() {

    int arr[] = {2, 4, 6, 8};
    int n = 4;

    cout << "Sum = " << arraySum(arr, 0, n);

    return 0;
}

Output

Sum = 20

Dry Run

arraySum(arr, 0, 4)
= 2 + arraySum(arr, 1, 4)
= 2 + 4 + arraySum(arr, 2, 4)
= 2 + 4 + 6 + arraySum(arr, 3, 4)
= 2 + 4 + 6 + 8 + arraySum(arr, 4, 4)
= 2 + 4 + 6 + 8 + 0
= 20

6. Find the Maximum Element in an Array

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

C++ Program

#include <iostream>
#include <algorithm>
using namespace std;

int findMaximum(int arr[], int index, int n) {

    // Base case: last element
    if (index == n - 1) {
        return arr[index];
    }

    // Find maximum in remaining elements
    int remainingMaximum = findMaximum(arr, index + 1, n);

    // Compare current element with remaining maximum
    return max(arr[index], remainingMaximum);
}

int main() {

    int arr[] = {12, 45, 23, 67, 34};
    int n = 5;

    cout << "Maximum = " << findMaximum(arr, 0, n);

    return 0;
}

Output

Maximum = 67

Note: This implementation assumes the array contains at least one element. For an empty array, handle that case separately before calling the function.

7. Find the Minimum Element in an Array

Finding the minimum element follows the same approach as finding the maximum. Instead of choosing the larger value, we choose the smaller value.

C++ Program

#include <iostream>
#include <algorithm>
using namespace std;

int findMinimum(int arr[], int index, int n) {

    // Base case
    if (index == n - 1) {
        return arr[index];
    }

    // Find minimum in remaining elements
    int remainingMinimum = findMinimum(arr, index + 1, n);

    // Compare current element with remaining minimum
    return min(arr[index], remainingMinimum);
}

int main() {

    int arr[] = {12, 45, 23, 67, 34};
    int n = 5;

    cout << "Minimum = " << findMinimum(arr, 0, n);

    return 0;
}

Output

Minimum = 12

8. Search an Element in an Array

We can search for an element recursively by checking the current array element and then searching the remaining elements.

If the element is found, return its index. If the index reaches the array size without finding the element, return -1.

C++ Program: Linear Search Using Recursion

#include <iostream>
using namespace std;

int recursiveSearch(int arr[], int index, int n, int target) {

    // Base case: element not found
    if (index == n) {
        return -1;
    }

    // Element found
    if (arr[index] == target) {
        return index;
    }

    // Search remaining elements
    return recursiveSearch(arr, index + 1, n, target);
}

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;
    int target = 30;

    int result = recursiveSearch(arr, 0, n, target);

    if (result != -1) {
        cout << "Element found at index " << result;
    } else {
        cout << "Element not found";
    }

    return 0;
}

Output

Element found at index 2

9. Reverse an Array Using Recursion

Printing an array in reverse order does not change the original array. To actually reverse the array, we can swap elements from both ends and recursively move toward the center.

We use two indexes:

  • left points to the beginning of the current range.
  • right points to the end of the current range.

When the left index becomes greater than or equal to the right index, the array has been reversed.

C++ Program

#include <iostream>
#include <algorithm>
using namespace std;

void reverseArray(int arr[], int left, int right) {

    // Base case
    if (left >= right) {
        return;
    }

    // Swap the two elements
    swap(arr[left], arr[right]);

    // Move toward the center
    reverseArray(arr, left + 1, right - 1);
}

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;

    reverseArray(arr, 0, n - 1);

    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output

50 40 30 20 10

Dry Run

Left Right Operation
0 4 Swap 10 and 50
1 3 Swap 20 and 40
2 2 Base case reached

10. Check Whether an Array Is Sorted

We can check whether an array is sorted in non-decreasing order by comparing adjacent elements.

If the current element is greater than the next element, the array is not sorted. Otherwise, we recursively check the remaining elements.

C++ Program

#include <iostream>
using namespace std;

bool isSorted(int arr[], int index, int n) {

    // Base case: zero or one element remains
    if (index >= n - 1) {
        return true;
    }

    // Current pair is out of order
    if (arr[index] > arr[index + 1]) {
        return false;
    }

    // Check the remaining array
    return isSorted(arr, index + 1, n);
}

int main() {

    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;

    if (isSorted(arr, 0, n)) {
        cout << "Array is sorted";
    } else {
        cout << "Array is not sorted";
    }

    return 0;
}

Output

Array is sorted

11. Recursive Array Problems: Different Approaches

The same array can be processed in different ways depending on the problem. Understanding these approaches helps us choose the correct recursive structure.

Approach How It Works Example
Forward traversal Process the current element before recursion Print array from left to right
Backward processing Process the current element after recursion Print array in reverse order
Two-pointer recursion Use two indexes moving toward each other Reverse an array
Return-based recursion Combine the current element with the recursive result Sum or maximum of an array

12. Time and Space Complexity

Recursive array operations often visit each element once. Their time complexity is therefore usually O(N). However, recursive calls use additional call stack memory.

Operation Time Complexity Auxiliary Space
Array traversal O(N) O(N)
Reverse printing O(N) O(N)
Array sum O(N) O(N)
Find maximum O(N) O(N)
Find minimum O(N) O(N)
Linear search O(N) O(N)
Reverse array O(N) O(N)
Check sorted array O(N) O(N)
Note: These space complexities describe the recursive call stack. Reversing the array modifies the original array in place, so it does not require another array, but it still uses O(N) stack space in this recursive implementation.

13. Iteration vs Recursion on Arrays

Feature Iteration Recursion
Technique Uses loops Uses recursive function calls
Termination Loop condition Base case
Extra stack memory Usually O(1) Depends on recursion depth
Readability Often simpler for basic traversal Can be natural for recursive problems
Risk Infinite loop Stack overflow

14. Common Mistakes

1. Incorrect Base Case

If the stopping condition is incorrect, the function may access an invalid array index or stop before processing all elements.

2. Forgetting to Increase the Index

In forward traversal, the recursive call should usually use index + 1. Otherwise, the same element may be processed repeatedly.

3. Accessing arr[n]

For an array of size N, the last valid index is N - 1. Accessing arr[n] is out of bounds.

4. Printing Before Instead of After the Recursive Call

Printing before recursion produces forward order. Printing after recursion produces reverse order. Choose the position based on the required output.

5. Not Handling Empty Arrays

Some functions, such as maximum and minimum, require at least one element. Handle an empty array separately instead of calling a function that assumes an element exists.

15. Applications of Recursion on Arrays

  • Searching for elements in arrays.
  • Calculating sums and products of array elements.
  • Finding maximum and minimum values.
  • Reversing arrays recursively.
  • Checking whether an array is sorted.
  • Solving divide-and-conquer problems such as Merge Sort and Quick Sort.
  • Generating subsets and combinations of array elements.
  • Solving backtracking problems involving choices from arrays.

16. Interview Questions

Q1. What is recursion on arrays?

It is a technique in which array elements are processed through recursive function calls, generally using an index to track the current position.

Q2. What is the common base case for array traversal?

When traversing from index 0 to the end, a common base case is index == n.

Q3. How can we print an array in reverse order using recursion?

Make the recursive call first and print the current element after the recursive call returns.

Q4. What is the time complexity of recursive array traversal?

It is O(N), because each element is visited once.

Q5. What is the auxiliary space complexity of recursive array traversal?

It is O(N), because up to N recursive calls can remain active on the call stack.

Q6. Can we reverse an array using recursion without creating another array?

Yes. Use two pointers, swap the elements at both ends, and recursively move the pointers toward the center.

Q7. Can recursion be used for binary search on an array?

Yes. Binary search can recursively divide a sorted array's search range into smaller halves.

17. Practice Problems

  1. Print all elements of an array using recursion.
  2. Print all array elements in reverse order.
  3. Find the sum of all elements in an array.
  4. Find the product of all elements in an array.
  5. Find the maximum element using recursion.
  6. Find the minimum element using recursion.
  7. Search for a given element using recursive linear search.
  8. Reverse an array in place using recursion.
  9. Check whether an array is sorted in non-decreasing order.
  10. Count how many times a given element appears in an array.
  11. Find the first occurrence of an element using recursion.
  12. Implement recursive binary search on a sorted array.

18. Summary

  • Recursion can process arrays one element at a time.
  • An index is commonly used to track the current position.
  • The base case prevents accessing elements beyond the array boundary.
  • Printing before recursion gives forward order; printing after recursion gives reverse order.
  • Recursive functions can calculate sums, find maximum and minimum values, and search arrays.
  • Two-pointer recursion can reverse an array in place.
  • Most simple recursive array operations take O(N) time and O(N) auxiliary stack space.
Key Takeaway: To solve an array problem using recursion, identify the current index, define the base case, process the current element, and make a recursive call on the remaining part of the array.
Scroll to Top