Bird
Raised Fist0
DSA Javaprogramming~10 mins

Recursion on Arrays and Strings in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - Recursion on Arrays and Strings
Start with full array/string
↓
Check base case: empty or size 1?
Yes→Return base result
No↓
Process current element or substring
↓
Call recursion on smaller array/string
↓
Combine current result with recursive call result
↓
Return combined result
Recursion breaks the array or string into smaller parts, processes one part, then calls itself on the rest until a simple base case is reached.
Execution Sample
DSA Java
int sum(int[] arr, int n) {
  if (n <= 0) return 0;
  return sum(arr, n-1) + arr[n-1];
}
This code calculates the sum of the first n elements of an array using recursion.
Execution Table
StepOperationnRecursive CallReturn ValueExplanation
1sum(arr, 3)3sum(arr, 2)Start with n=3, calls sum(arr,2)
2sum(arr, 2)2sum(arr, 1)n=2, calls sum(arr,1)
3sum(arr, 1)1sum(arr, 0)n=1, calls sum(arr,0)
4sum(arr, 0)0None0Base case reached, returns 0
5Return from sum(arr, 0)00Returns 0 to sum(arr,1)
6Calculate sum(arr,1)10 + arr[0] = 0 + 1 = 1Adds arr[0]=1
7Return from sum(arr,1)11Returns 1 to sum(arr,2)
8Calculate sum(arr,2)21 + arr[1] = 1 + 2 = 3Adds arr[1]=2
9Return from sum(arr,2)23Returns 3 to sum(arr,3)
10Calculate sum(arr,3)33 + arr[2] = 3 + 3 = 6Adds arr[2]=3
11Return from sum(arr,3)36Final result 6 returned
💡 Recursion stops when n reaches 0, the base case.
Variable Tracker
VariableStartAfter Step 4After Step 6After Step 8After Step 10Final
n301233
Return Value01366
Key Moments - 3 Insights
Why does the recursion stop at n=0 and not n=1?
Because the base case is defined as n <= 0 (step 4), which returns 0 immediately. This prevents infinite recursion and starts the return chain.
How does the function combine results from recursive calls?
At each return step (steps 6, 8, 10), the function adds the current array element arr[n-1] to the result returned by the recursive call sum(arr, n-1).
What happens if the array is empty?
If the array is empty, n=0 initially, so the base case triggers immediately (step 4), returning 0 without further calls.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the return value at step 8?
A1
B6
C3
D0
💡 Hint
Check the 'Return Value' column at step 8 in the execution_table.
At which step does the base case trigger and stop recursion?
AStep 4
BStep 6
CStep 3
DStep 10
💡 Hint
Look for the step where n=0 and no further recursive call is made.
If the array was empty (n=0), what would be the return value immediately?
A1
B0
CArray length
DError
💡 Hint
Refer to the base case return value in the execution_table at step 4.
Concept Snapshot
Recursion on Arrays and Strings:
- Base case stops recursion (e.g., empty or size 0)
- Process current element
- Recursively call on smaller array/string
- Combine current result with recursive call
- Returns final combined result
Full Transcript
Recursion on arrays and strings works by breaking the problem into smaller parts. We check a base case, usually when the size is zero or one, to stop recursion. Then we process the current element and call the function again on the smaller part. Each recursive call returns a result that is combined with the current element's processing. For example, summing an array recursively adds the last element to the sum of the rest. The recursion stops when the base case is reached, and results return back up the call stack.

Practice

(1/5)
1. What does a recursive function on an array typically do to process the elements?
easy
A. It calls itself with a smaller part of the array until a base case is reached
B. It uses loops to iterate over the array elements
C. It modifies the array without calling itself
D. It sorts the array before processing

Solution

  1. Step 1: Understand recursion on arrays

    Recursive functions reduce the problem size by calling themselves with smaller parts of the array.
  2. Step 2: Identify base case and recursive call

    The function stops when the array part is empty or has one element (base case), otherwise it calls itself with a smaller array.
  3. Final Answer:

    It calls itself with a smaller part of the array until a base case is reached -> Option A
  4. Quick Check:

    Recursion = smaller problem calls [OK]
Hint: Recursion breaks problem into smaller parts until simple case [OK]
Common Mistakes:
  • Thinking recursion uses loops instead of self-calls
  • Ignoring the base case in recursion
  • Assuming recursion sorts the array automatically
2. Which of the following is the correct syntax to define a recursive method in Java that takes an integer array and an index as parameters?
easy
A. void recurse(int arr[], index int) { ... }
B. public void recurse(int[] arr, int index) { ... }
C. public int recurse(int arr, int index) { ... }
D. public void recurse(int[] arr; int index) { ... }

Solution

  1. Step 1: Check Java method syntax

    Java methods require return type, method name, and parameters with types and commas.
  2. Step 2: Validate parameter types and order

    public void recurse(int[] arr, int index) { ... } correctly uses 'int[] arr' and 'int index' separated by a comma and proper method signature.
  3. Final Answer:

    public void recurse(int[] arr, int index) { ... } -> Option B
  4. Quick Check:

    Java method syntax = returnType name(type1 param1, type2 param2) [OK]
Hint: Remember Java method parameters need types and commas [OK]
Common Mistakes:
  • Using wrong parameter order or missing commas
  • Incorrect array parameter syntax
  • Missing return type in method definition
3. What will be the output of the following Java code?
public class Test {
  public static void printArray(int[] arr, int index) {
    if (index == arr.length) return;
    System.out.print(arr[index] + " ");
    printArray(arr, index + 1);
  }
  public static void main(String[] args) {
    int[] nums = {1, 2, 3};
    printArray(nums, 0);
  }
}
medium
A. Compilation error
B. 3 2 1
C. 1 2 3 0
D. 1 2 3

Solution

  1. Step 1: Trace the recursive calls

    printArray prints arr[index] then calls itself with index+1 until index equals arr.length (3).
  2. Step 2: Output elements in order

    It prints 1, then 2, then 3, then stops without extra output.
  3. Final Answer:

    1 2 3 -> Option D
  4. Quick Check:

    Recursion prints array elements in order [OK]
Hint: Recursion prints then calls next index until end [OK]
Common Mistakes:
  • Expecting reverse order output
  • Thinking extra elements print after recursion ends
  • Confusing base case condition
4. Identify the error in this recursive method that tries to sum elements of an integer array:
public int sumArray(int[] arr, int index) {
  if (index > arr.length) return 0;
  return arr[index] + sumArray(arr, index + 1);
}
medium
A. Array parameter should be List<Integer>
B. Method should return void instead of int
C. Base case condition should be index >= arr.length
D. Recursive call should use index - 1

Solution

  1. Step 1: Check base case condition

    Index should stop recursion when it reaches arr.length, so condition must be index >= arr.length.
  2. Step 2: Understand array bounds

    Using index > arr.length allows index == arr.length, which causes ArrayIndexOutOfBoundsException.
  3. Final Answer:

    Base case condition should be index >= arr.length -> Option C
  4. Quick Check:

    Base case must prevent out-of-bounds access [OK]
Hint: Base case index must not exceed array length [OK]
Common Mistakes:
  • Using wrong base case condition causing runtime error
  • Changing return type incorrectly
  • Incorrect recursive index update
5. Given a string, write a recursive method to check if it is a palindrome (reads the same forwards and backwards). Which approach correctly describes the recursion?
hard
A. Compare first and last characters, then recurse on substring excluding them
B. Reverse the string using recursion and compare with original
C. Count characters recursively and check if count is even
D. Use recursion to sort characters and check equality

Solution

  1. Step 1: Understand palindrome check logic

    Check if first and last characters match, then check the substring inside recursively.
  2. Step 2: Identify correct recursive approach

    Compare first and last characters, then recurse on substring excluding them matches this logic, reducing problem size each call until base case (empty or one char string).
  3. Final Answer:

    Compare first and last characters, then recurse on substring excluding them -> Option A
  4. Quick Check:

    Palindrome recursion = compare ends, recurse inside substring [OK]
Hint: Check ends match, then recurse inside substring [OK]
Common Mistakes:
  • Trying to reverse string recursively instead of comparing ends
  • Counting characters instead of comparing
  • Sorting characters which changes original order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard