Recursive Traversal of Strings and Collections
Determining the results of recursive algorithms that traverse String objects, arrays, and ArrayList objects: first letter and rest, index parameters, base cases for sequences, and how the position of the work changes the order of the traversal.
Recursion can be used to traverse String objects, arrays, and ArrayList objects. Each call handles one piece, usually the first letter or the element at an index, and passes the rest of the sequence to the next call. For strings, the rest is a shorter substring; for arrays and lists, it is the same collection with an index one larger. The traversal stops at a base case such as an empty string or an index equal to the length, and work placed before or after the recursive call processes the elements forward or backward.
1One Piece and the Rest
A loop traverses a sequence by moving a variable from one position to the next. A recursive traversal reaches the same elements in a different way: each call deals with one element and makes a recursive call to deal with everything after it. The problem shrinks by one element per call, so after as many calls as there are elements, nothing remains, and the base case returns.
How "the rest" is described depends on the type. A string can be cut into a shorter string with substring, so each call receives a smaller string. An array or ArrayList is usually not cut; instead, every call receives the same collection plus an index that marks where its part begins.
| Collection | This call handles | Next call receives | Base case |
|---|---|---|---|
| String | s.substring(0, 1) | s.substring(1) | s.length() == 0 (or ≤ 1) |
| Array | a[i] | the same array and i + 1 | i == a.length |
| ArrayList | list.get(i) | the same list and i + 1 | i == list.size() |
| Loop traversal | Recursive traversal |
|---|---|
Loop variable i starts at 0 | First call passes i = 0 |
Condition i < a.length | Base case i == a.length stops the calls |
i++ at the end of each pass | Recursive call with i + 1 |
| Running total in a variable | Each call returns its element plus the result for the rest |
2Traversing Strings
For a string s, s.substring(0, 1) is its first letter and s.substring(1) is everything after it. A recursive method handles the first letter and passes s.substring(1) to the next call, which is one letter shorter. The base case is a string short enough to answer directly: the empty string, with length 0, or a string of length 1.
Because strings are immutable, none of these calls changes the original string. Each substring call creates a new, shorter string, and methods such as reverse build and return a new result. The original variable still refers to the original text afterward.
Tracing a string traversal is easiest with a column of arguments: write the string passed to each call, one letter shorter each time, until the base case. Then fill in what each call returns or prints, working in the direction the code dictates: down the column for work done before the recursive call, and back up the column for work done after it.
substring(0, 1) gives the first letter and substring(1) gives the rest, which is passed to the next call.Reversing With substring
Predict the output (Figure 2).
public static String reverse(String s)
{
if (s.length() <= 1)
{
return s;
}
return reverse(s.substring(1)) + s.substring(0, 1);
}
enots
stone
- 1Base case: a string of length 0 or 1 is its own reverse.
- 2Recursive call: reverse the rest,
s.substring(1), then add the first letter at the end. - 3Strings are immutable:
wordstill refers to "stone"; the method built new strings.
Printing Every Ending
Predict the output.
public static void endings(String s)
{
if (s.length() > 0)
{
System.out.println(s);
endings(s.substring(1));
}
}
dusk
usk
sk
k
- 1Each call prints its whole string first, then passes everything after the first letter.
- 2The strings shrink: "dusk", "usk", "sk", "k", then "", where the condition is false and nothing happens.
| Call | First letter | Count for the rest | Returns |
|---|---|---|---|
| countOf("banana") | b | 3 | 3 |
| countOf("anana") | a | 2 | 3 |
| countOf("nana") | n | 2 | 2 |
| countOf("ana") | a | 1 | 2 |
| countOf("na") | n | 1 | 1 |
| countOf("a") | a | 0 | 1 |
| countOf("") | — | — | 0 (base case) |
Counting a Letter
Predict the output.
public static int countOf(String s, String letter)
{
if (s.length() == 0)
{
return 0;
}
int rest = countOf(s.substring(1), letter);
if (s.substring(0, 1).equals(letter))
{
return rest + 1;
}
return rest;
}
3
0
- 1Base case: the empty string contains no letters: 0.
- 2Each call first counts the rest, then adds 1 if its own first letter matches (trace below).
"".substring(1) throws a StringIndexOutOfBoundsException, because index 1 is past the end. The base case must catch the empty string before any substring call is made.
String works on a shorter substring in each call until a base case is reached.3Traversing Arrays
Arrays are traversed recursively with an index parameter. The call sumFrom(a, i) handles a[i] and asks sumFrom(a, i + 1) for the rest. The first call usually passes 0, and the base case is i == a.length, the first index past the end, where no elements remain.
Every call shares the same array object; only the index differs. Tracing such a method means listing the index for each call and the value that call returns, from the base case back to the first call, as in Figure 3. Starting with a different index processes only part of the array.
Summing From an Index
Predict the output (Figure 3).
public static int sumFrom(int[] a, int i)
{
if (i == a.length)
{
return 0;
}
return a[i] + sumFrom(a, i + 1);
}
21
8
- 1The index parameter marks where this call starts; the array itself is shared by every call.
- 2Base case:
i == a.lengthmeans no elements remain: 0. - 3Starting at 2 sums only the last two elements: 2 + 6 = 8.
The Largest Element
Predict the output.
public static int maxFrom(int[] a, int i)
{
if (i == a.length - 1)
{
return a[i];
}
int restMax = maxFrom(a, i + 1);
if (a[i] > restMax)
{
return a[i];
}
return restMax;
}
9
- 1Base case: the last element alone is the largest of a one-element portion: 6.
- 2Coming back: 2 vs 6 gives 6; 9 vs 6 gives 9; 4 vs 9 gives 9.
Stopping One Index Too Late
The base case below is off by one. What happens?
public static int sumBad(int[] a, int i)
{
if (i > a.length)
{
return 0;
}
return a[i] + sumBad(a, i + 1);
}
- 1When
iis 4, the conditioni > a.lengthis false, so the method readsa[4]. - 2Index 4 does not exist in a 4-element array:
ArrayIndexOutOfBoundsException. - 3The fix:
if (i == a.length), the first index past the end.
ArrayIndexOutOfBoundsException. The base case of an index traversal must be reached exactly when no elements remain.A base case of i > a.length lets a call with i == a.length read a[a.length], which throws an ArrayIndexOutOfBoundsException. Stop at i == a.length.
4Traversing ArrayLists
ArrayList objects are traversed the same way, with list.get(i) for the current element and i == list.size() as the base case. A recursive linear search checks the element at i and, if it is not a match, searches the rest by calling itself with i + 1; it has two base cases, one for running out of elements and one for finding the target.
The order in which elements are processed depends on where the work sits. If a call processes its element before the recursive call, the elements are handled from first to last. If it processes its element after the recursive call, each element waits until all later elements are finished, so they are handled from last to first.
Printing Forward and Backward
Predict the output.
public static void forward(ArrayList<String> list, int i)
{
if (i < list.size())
{
System.out.println(list.get(i));
forward(list, i + 1);
}
}
public static void backward(ArrayList<String> list, int i)
{
if (i < list.size())
{
backward(list, i + 1);
System.out.println(list.get(i));
}
}
gate
bridge
summit
summit
bridge
gate
- 1
forwardprints before its call, so elements appear in index order. - 2
backwardprints after its call, so each element waits until all later elements are printed: reverse order. - 3Base case:
i == list.size()does nothing.
A Recursive Linear Search
Predict the output.
public static boolean contains(ArrayList<String> list, String target, int i)
{
if (i == list.size())
{
return false;
}
if (list.get(i).equals(target))
{
return true;
}
return contains(list, target, i + 1);
}
true
false
- 1Two base cases. Past the end:
false. A match:true, with no further calls. - 2Otherwise the search continues with the next index.
When the print statement follows the recursive call, the last element is printed first. Trace the calls all the way down before writing any output, then write the output as the calls return.
5Traversing From Both Ends
Some recursive traversals shrink a sequence from both ends at once. A palindrome check compares the first and last letters; if they differ, the answer is false immediately, and if they match, the method checks the substring between them, s.substring(1, s.length() - 1). Each call removes two letters, so the base case is a string of length 0 or 1.
The same outside-in pattern works for arrays with two index parameters, one moving forward from the start and one moving backward from the end, with a base case when they meet or cross.
Palindromes From the Outside In
Predict the output (Figure 4).
public static boolean isPalindrome(String s)
{
if (s.length() <= 1)
{
return true;
}
String first = s.substring(0, 1);
String last = s.substring(s.length() - 1);
if (!first.equals(last))
{
return false;
}
return isPalindrome(s.substring(1, s.length() - 1));
}
true
false
- 1"level": l = l, so check "eve"; e = e, so check "v"; length 1 returns
true. - 2"lever": the first letter, "l", and the last letter, "r", differ, so the method returns
falseat once without another call.
6Choosing and Checking Base Cases
For sequences, the base case is almost always "nothing left" or "one item left". For strings, that is s.length() == 0 or s.length() <= 1; for arrays and lists traversed by index, it is an index equal to the length or size, or, for methods like maxFrom that need at least one element, an index equal to the last position.
To check a base case while tracing, ask two questions: does every call move closer to it, and does it trigger before any invalid access? A method that reads a[i] or calls substring before testing its base case will fail on the last call.
The recursive call should receive i + 1. Each call's i is its own local copy, so the calling method still has its original index when the recursive call returns, which is exactly what after-call work relies on.
Four Habits for Recursive Traversals
1. Name the Piece and the Rest
First letter or a[i]; substring(1) or i + 1.
2. Base Case First
Before any substring or index access.
3. Before or After?
It decides forward or backward order.
4. Trace Down, Then Up
List the calls, then the returns.
Recursion can be used to traverse String objects, arrays, and ArrayList objects. A recursive traversal handles one element or letter per call and passes the rest of the sequence to the next call, either as a shorter substring or as the same collection with a larger index, until a base case such as an empty string or an index equal to the length is reached. The result is determined by tracing the calls down to the base case and then combining the returned values on the way back up.