Recursion on arrays and strings
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When beginners write recursive methods on an array or String, they often copy a smaller slice on every call (Arrays.copyOfRange(arr, 1, n) or s.substring(1)). Because each copy takes O(n) time and memory, n recursive steps silently balloon from O(n) into O(n²)! Passing index parameters keeps the original array or string untouched and runs in O(n) time.
Sum and max with an index
To recurse across an array arr without copying it, pass the current starting index idx (initially 0). The subproblem sumFrom(arr, idx) means.
Example 1 · Recursive array sum and array max using an index helper
public class ArrayRecursionDemo { public static int sum(int[] arr) { return sumFrom(arr, 0); }
private static int sumFrom(int[] arr, int idx) { if (idx == arr.length) return 0; return arr[idx] + sumFrom(arr, idx + 1); }
public static int max(int[] arr) { return maxFrom(arr, 0); }
private static int maxFrom(int[] arr, int idx) { if (idx == arr.length - 1) return arr[idx]; return Math.max(arr[idx], maxFrom(arr, idx + 1)); }
public static void main(String[] args) { int[] nums = {14, 7, 29, 3, 18}; System.out.println("Sum: " + sum(nums)); System.out.println("Max: " + max(nums)); }}Sum: 71 Max: 29
What this code does
- Public methods sum(arr) and max(arr) hide the starting index 0 from the caller.
- Each step advances idx by 1 in O(1) time without copying the array.
"return the sum of the suffix arr[idx .. n - 1]":
- Base case: when
idx == arr.length, the suffix is empty, so return0. - Recursive case: return
arr[idx] + sumFrom(arr, idx + 1). Similarly, to find the maximum element in a non-empty array fromidxonward (maxFrom(arr, idx)): - Base case: when
idx == arr.length - 1(the last element), returnarr[idx]. - Recursive case: return
Math.max(arr[idx], maxFrom(arr, idx + 1)). - Passing
idx + 1shrinks the remaining suffix[idx .. n - 1]in O(1) time per step. - Never call
Arrays.copyOfRangeinside a linear recursion—that turns O(n) into O(n²) time and space.
Reverse a string
How do you reverse a char[] (or build a reversed String) recursively?
- In-place on
char[]: pass two pointersleftandright(initially0andchars.length - 1).
Example 2 · Reversing a char[] in-place and reversing a String in O(n) with a StringBuilder helper
public class ReverseRecursiveDemo { public static void reverseChars(char[] a, int left, int right) { if (left >= right) return; char tmp = a[left]; a[left] = a[right]; a[right] = tmp; reverseChars(a, left + 1, right - 1); }
public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s.length()); reverseInto(s, 0, sb); return sb.toString(); }
private static void reverseInto(String s, int idx, StringBuilder sb) { if (idx == s.length()) return; reverseInto(s, idx + 1, sb); sb.append(s.charAt(idx)); // runs during unwinding (n-1 down to 0)! }
public static void main(String[] args) { char[] chars = "mentor".toCharArray(); reverseChars(chars, 0, chars.length - 1); System.out.println(new String(chars) + " | " + reverseString("algorithm")); }}rotnem | mhtirogla
What this code does
- reverseChars swaps outer pairs and recurses inward in n / 2 calls.
- reverseInto uses post-call unwinding to append characters into a single pre-sized StringBuilder in O(n) total time.
If left >= right, stop (base case); otherwise swap chars[left] and chars[right] and recurse on (left + 1, right - 1)!
- Building a reversed string: pass a shared
StringBuilderand indexidx, appendings.charAt(idx)after the recursive callreverseInto(s, idx + 1, sb)during the unwinding phase in O(n) total time.
return reverse(s.substring(1)) + s.charAt(0); in production or large inputs: both s.substring(1) and + allocate a new String of length O(n) at every step, costing O(n²) time!Palindrome check
A string s is a palindrome if and only if:
- Its first character
s.charAt(left)equals its last characters.charAt(right), and - The inner substring
s[left + 1 .. right - 1]is also a palindrome!
- Base case:
if (left >= right) return true;(0 or 1 character left in the middle is always a palindrome). - Mismatch check:
if (s.charAt(left) != s.charAt(right)) return false;(stops immediately on the first mismatch!). - Recursive step:
return isPalindrome(s, left + 1, right - 1);.
Example 3 · Recursive palindrome check with public wrapper and two-pointer helper
public class PalindromeRecursiveDemo { public static boolean isPalindrome(String s) { return isPalHelper(s, 0, s.length() - 1); }
private static boolean isPalHelper(String s, int left, int right) { if (left >= right) return true; if (s.charAt(left) != s.charAt(right)) return false; return isPalHelper(s, left + 1, right - 1); }
public static void main(String[] args) { System.out.println("racecar: " + isPalindrome("racecar")); System.out.println("noon: " + isPalindrome("noon")); System.out.println("robot: " + isPalindrome("robot")); }}racecar: true noon: true robot: false
What this code does
- For odd length ('racecar'), left and right meet at left == right == 3.
- For even length ('noon'), left and right cross at left = 2, right = 1; left >= right handles both cases!
That definition translates line-for-line into a two-pointer recursive method isPalindrome(s, left, right):
Helper methods with extra parameters
The standard Java pattern is a public wrapper method that validates edge cases and delegates to a private recursive helper method carrying the extra index or accumulator parameters.
public static int countChar(String s, char target) { if (s == null) return 0; // the wrapper checks edge cases return countFrom(s, target, 0); // and hides the start index}
private static int countFrom(String s, char target, int i) { if (i == s.length()) return 0; int here = s.charAt(i) == target ? 1 : 0; return here + countFrom(s, target, i + 1);}Callers of your class want a clean public signature like public static boolean isPalindrome(String s) or public static int arraySum(int[] arr)—they shouldn't have to pass 0 and s.length() - 1 themselves!
Next step
Check your understanding
10 quick questions