Recursion on Arrays and Strings in DSA Java - Time & Space Complexity
When using recursion on arrays or strings, it is important to understand how the number of steps grows as the input size increases.
We want to know how many times the function calls itself and processes parts of the input.
Analyze the time complexity of the following code snippet.
public int sumArray(int[] arr, int index) {
if (index == arr.length) {
return 0;
}
return arr[index] + sumArray(arr, index + 1);
}
This code calculates the sum of all elements in an array using recursion by moving from the current index to the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive call that processes one element of the array at a time.
- How many times: Once for each element in the array, so n times if the array length is n.
Each recursive call handles one element, so the total steps grow directly with the array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 recursive calls |
| 100 | About 100 recursive calls |
| 1000 | About 1000 recursive calls |
Pattern observation: The number of operations grows linearly as the input size increases.
Time Complexity: O(n)
This means the time to complete grows in direct proportion to the size of the array.
[X] Wrong: "Recursion here is faster because it avoids loops."
[OK] Correct: Both recursion and loops here do the same amount of work; recursion just uses function calls instead of explicit loops.
Understanding how recursion processes each element helps you explain your code clearly and reason about efficiency in interviews.
"What if we changed the recursion to process two elements per call instead of one? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursion on arrays
Recursive functions reduce the problem size by calling themselves with smaller parts of the array.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.Final Answer:
It calls itself with a smaller part of the array until a base case is reached -> Option AQuick Check:
Recursion = smaller problem calls [OK]
- Thinking recursion uses loops instead of self-calls
- Ignoring the base case in recursion
- Assuming recursion sorts the array automatically
Solution
Step 1: Check Java method syntax
Java methods require return type, method name, and parameters with types and commas.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.Final Answer:
public void recurse(int[] arr, int index) { ... } -> Option BQuick Check:
Java method syntax = returnType name(type1 param1, type2 param2) [OK]
- Using wrong parameter order or missing commas
- Incorrect array parameter syntax
- Missing return type in method definition
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);
}
}Solution
Step 1: Trace the recursive calls
printArray prints arr[index] then calls itself with index+1 until index equals arr.length (3).Step 2: Output elements in order
It prints 1, then 2, then 3, then stops without extra output.Final Answer:
1 2 3 -> Option DQuick Check:
Recursion prints array elements in order [OK]
- Expecting reverse order output
- Thinking extra elements print after recursion ends
- Confusing base case condition
public int sumArray(int[] arr, int index) {
if (index > arr.length) return 0;
return arr[index] + sumArray(arr, index + 1);
}Solution
Step 1: Check base case condition
Index should stop recursion when it reaches arr.length, so condition must be index >= arr.length.Step 2: Understand array bounds
Using index > arr.length allows index == arr.length, which causes ArrayIndexOutOfBoundsException.Final Answer:
Base case condition should be index >= arr.length -> Option CQuick Check:
Base case must prevent out-of-bounds access [OK]
- Using wrong base case condition causing runtime error
- Changing return type incorrectly
- Incorrect recursive index update
Solution
Step 1: Understand palindrome check logic
Check if first and last characters match, then check the substring inside recursively.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).Final Answer:
Compare first and last characters, then recurse on substring excluding them -> Option AQuick Check:
Palindrome recursion = compare ends, recurse inside substring [OK]
- Trying to reverse string recursively instead of comparing ends
- Counting characters instead of comparing
- Sorting characters which changes original order
Ready to prove it?
Pass the test and this pattern moves unknown
