AP Computer Science A · Study guide

Recursive String and Collection Traversal

AP® Computer Science A · Data Collections

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.

Big Picture

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.

CollectionThis call handlesNext call receivesBase case
Strings.substring(0, 1)s.substring(1)s.length() == 0 (or ≤ 1)
Arraya[i]the same array and i + 1i == a.length
ArrayListlist.get(i)the same list and i + 1i == list.size()
Loop traversalRecursive traversal
Loop variable i starts at 0First call passes i = 0
Condition i < a.lengthBase case i == a.length stops the calls
i++ at the end of each passRecursive call with i + 1
Running total in a variableEach 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.

Figure 1. substring(0, 1) gives the first letter and substring(1) gives the rest, which is passed to the next call.
Worked Example 1 Strings

Reversing With substring

Predict the output (Figure 2).

Code
public static String reverse(String s)
{
    if (s.length() <= 1)
    {
        return s;
    }
    return reverse(s.substring(1)) + s.substring(0, 1);
}
Output
enots
stone
  1. 1Base case: a string of length 0 or 1 is its own reverse.
  2. 2Recursive call: reverse the rest, s.substring(1), then add the first letter at the end.
  3. 3Strings are immutable: word still refers to "stone"; the method built new strings.
Result: The output is enots, then stone. Recursion traverses a string by handling its first letter and passing the rest to the next call.
Worked Example 2 Strings

Printing Every Ending

Predict the output.

Code
public static void endings(String s)
{
    if (s.length() > 0)
    {
        System.out.println(s);
        endings(s.substring(1));
    }
}
Output
dusk
usk
sk
k
  1. 1Each call prints its whole string first, then passes everything after the first letter.
  2. 2The strings shrink: "dusk", "usk", "sk", "k", then "", where the condition is false and nothing happens.
Result: The output is dusk, usk, sk, and k. The sequence of arguments, each one letter shorter, is the record of the traversal's progress.
CallFirst letterCount for the restReturns
countOf("banana")b33
countOf("anana")a23
countOf("nana")n22
countOf("ana")a12
countOf("na")n11
countOf("a")a01
countOf("")——0 (base case)
Worked Example 3 Strings

Counting a Letter

Predict the output.

Code
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;
}
Output
3
0
  1. 1Base case: the empty string contains no letters: 0.
  2. 2Each call first counts the rest, then adds 1 if its own first letter matches (trace below).
Result: The output is 3 and 0. A recursive count combines the result for the rest of the string with a check of the first letter.
Common Mistake 1 · Calling substring(1) on an Empty String

"".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.

Figure 2. A recursive traversal of a 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.

Figure 3. Recursion traverses an array with an index parameter that moves one position per call; the base case is reached when the index passes the last element.
Worked Example 4 Arrays

Summing From an Index

Predict the output (Figure 3).

Code
public static int sumFrom(int[] a, int i)
{
    if (i == a.length)
    {
        return 0;
    }
    return a[i] + sumFrom(a, i + 1);
}
Output
21
8
  1. 1The index parameter marks where this call starts; the array itself is shared by every call.
  2. 2Base case: i == a.length means no elements remain: 0.
  3. 3Starting at 2 sums only the last two elements: 2 + 6 = 8.
Result: The output is 21 and 8. Recursion traverses an array with an index parameter that increases by 1 in each call.
Worked Example 5 Arrays

The Largest Element

Predict the output.

Code
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;
}
Output
9
  1. 1Base case: the last element alone is the largest of a one-element portion: 6.
  2. 2Coming back: 2 vs 6 gives 6; 9 vs 6 gives 9; 4 vs 9 gives 9.
Result: The output is 9. Each call compares its own element with the largest element of the rest of the array.
Worked Example 6 Base case errors

Stopping One Index Too Late

The base case below is off by one. What happens?

Code
public static int sumBad(int[] a, int i)
{
    if (i > a.length)
    {
        return 0;
    }
    return a[i] + sumBad(a, i + 1);
}
  1. 1When i is 4, the condition i > a.length is false, so the method reads a[4].
  2. 2Index 4 does not exist in a 4-element array: ArrayIndexOutOfBoundsException.
  3. 3The fix: if (i == a.length), the first index past the end.
Result: The program stops with an ArrayIndexOutOfBoundsException. The base case of an index traversal must be reached exactly when no elements remain.
Common Mistake 2 · A Base Case One Index Late

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.

Worked Example 7 ArrayList

Printing Forward and Backward

Predict the output.

Code
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));
    }
}
Output
gate
bridge
summit
summit
bridge
gate
  1. 1forward prints before its call, so elements appear in index order.
  2. 2backward prints after its call, so each element waits until all later elements are printed: reverse order.
  3. 3Base case: i == list.size() does nothing.
Result: The output is gate, bridge, summit, then summit, bridge, gate. The position of the work relative to the recursive call decides the order of the traversal.
Worked Example 8 ArrayList

A Recursive Linear Search

Predict the output.

Code
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);
}
Output
true
false
  1. 1Two base cases. Past the end: false. A match: true, with no further calls.
  2. 2Otherwise the search continues with the next index.
Result: The output is true and false. A linear search can be expressed recursively: each call checks one element and passes the rest on.
Common Mistake 3 · Expecting After-Call Work in Forward Order

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.

Figure 4. A recursive palindrome check compares the first and last letters and, if they match, checks the substring between them.
Worked Example 9 Strings

Palindromes From the Outside In

Predict the output (Figure 4).

Code
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));
}
Output
true
false
  1. 1"level": l = l, so check "eve"; e = e, so check "v"; length 1 returns true.
  2. 2"lever": the first letter, "l", and the last letter, "r", differ, so the method returns false at once without another call.
Result: The output is true and false. Each call compares the outer letters and passes the substring between them to the next 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.

Common Mistake 4 · Changing the Shared Index Instead of Passing a New One

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.

Core Synthesis

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.