Recursion on lists and strings
After this: Add up a list and reverse a string by trusting the smaller call.
On this page · 7 sections · 3 checks
So far the input has been a number that gets smaller: 3, 2, 1, 0. A list can get smaller too, and so can a string. This lesson uses recursion on both, and it adds up a list with no loop at all.
It also shows the way most people write recursion. When Chen told you a place in the line, you did not check how Chen found out. You took the answer and added one. Writing a recursive function works in the same way.
Adding up a list
A list of three items is one item followed by a list of two items. So the sum of [1, 2, 3] is 1 plus the sum of [2, 3]. The sum of the rest is the same problem on a shorter list, which makes it a smaller copy.
The smallest list is the empty list. Its sum is 0, and that is the base case.
def sum_list(items): if not items: # base case: nothing left to add return 0 return items[0] + sum_list(items[1:]) # the first item, plus the sum of the rest
print(sum_list([1, 2, 3]))6
static int sumList(List<Integer> items) { if (items.isEmpty()) return 0; // base case: nothing left to add return items.get(0) + sumList(items.subList(1, items.size())); // the first item, plus the sum of the rest}
System.out.println(sumList(List.of(1, 2, 3)));6
items[1:]items.subList(1, items.size()) means "the list from index 1 to the end", which is everything after the first item. An index is a position in the list, and the first item has index 0.
Here is the run for [1, 2, 3].
- To sum
[1, 2, 3], the function needs the sum of[2, 3]. - To sum
[2, 3], it needs the sum of[3]. - To sum
[3], it needs the sum of[]. []is the base case. Its sum is 0.- The sum of
[3]is 3 + 0 = 3. - The sum of
[2, 3]is 2 + 3 = 5. - The sum of
[1, 2, 3]is 1 + 5 = 6.
Trust the smaller call
You traced every level above, and that is a good way to see what the computer does. But you do not need to do it when you write a recursive function.
Instead, write the recursive case as if the smaller call already works. Ask only one question: if I am given the right answer for the rest, how do I finish my part? For the sum, the answer is "add my first item". We call this habit trusting the smaller call.
Why is it safe? The smaller call is the same code, on an input one step nearer the base case. The base case gives the right answer for the empty list. If the function is right for a list of some length, the recursive case makes it right for a list one item longer. So it is right for length 1, then for length 2, and for every length after that.
Strings shrink the same way
To reverse a string, reverse the rest of it, then put the first character at the end. A string of one character or none is already its own reverse, so that is the base case.
def reverse(s): if len(s) <= 1: # base case: one character or none return s return reverse(s[1:]) + s[0] # the rest reversed, then the first character at the end
print(reverse("abc"))cba
static String reverse(String s) { if (s.length() <= 1) return s; // base case: one character or none return reverse(s.substring(1)) + s.charAt(0); // the rest reversed, then the first character at the end}
System.out.println(reverse("abc"));cba
s[1:]s.substring(1) means "the string without its first character". Here is the run for "abc".
- The reverse of
"abc"is the reverse of"bc", then"a". - The reverse of
"bc"is the reverse of"c", then"b". "c"has one character, so it is the base case. It returns"c".- Going back, the reverse of
"bc"is"c"+"b"="cb". - The reverse of
"abc"is"cb"+"a"="cba".
If you trust the smaller call, you need only one line of this: the reverse of "bc" is "cb", so the answer is "cb" + "a".
Watch it happen
The visualizer labels the first function sum and the second reverse.
- sum([1, 2, 3])Sum [1, 2, 3]. Each frame passes the rest of the list to a smaller call. It adds its first item when the sum of the rest comes back.
- reverse("abc")
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
Each frame holds a shorter list or string than the frame below it. The top frame holds the base case: the empty list, or a single character. From there the answers come back, and each frame adds its own item.
The cost of copying the rest
Adding up a list should take about one step for each item. We call that O(n), which means the work grows at the same rate as the size of the list. Counting steps explains this notation.
But our code does more work than that, because taking "the rest" can make a copy. In Python, items[1:] is called a slice. It builds a new list, and s[1:] builds a new string. In Java, s.substring(1) builds a new string too.
Take a string of 4 characters. The first call copies 3 characters, the next copies 2, and the next copies 1. That is 3 + 2 + 1 = 6 characters copied, to reverse a string of 4.
For n items, the total is (n − 1) + (n − 2) + … + 1, which is about n²/2. That is O(n²), which means that when the input doubles, the work grows about four times. For 1,000 items, it is about 500,000 copies.
There is a way to avoid this. Keep the same list, and pass an index that says where the rest starts. Nothing is copied.
def sum_from(items, i): if i == len(items): # base case: past the last item return 0 return items[i] + sum_from(items, i + 1) # no slice: the index says where the rest starts
print(sum_from([1, 2, 3], 0))6
static int sumFrom(int[] items, int i) { if (i == items.length) return 0; // base case: past the last item return items[i] + sumFrom(items, i + 1); // no copy: the index says where the rest starts}
System.out.println(sumFrom(new int[] {1, 2, 3}, 0));6
The function starts with i at 0. Each call adds items[i] and asks for the sum from i + 1. When i equals the length of the list, it has gone past the last item, so that is the base case. All the calls share one list, and only i changes.
Check yourself
You are writing sum_listsumList for [1, 2, 3]. You assume that sum_list([2, 3])sumList(List.of(2, 3)) returns 5, and you do not check it. Why is that safe?
This looks like reverse, but one thing has changed. What does it print?
def mystery(s): if len(s) <= 1: return s return s[0] + mystery(s[1:])
print(mystery("abc"))static String mystery(String s) { if (s.length() <= 1) return s; return s.charAt(0) + mystery(s.substring(1));}
System.out.println(mystery("abc"));reverse on a string of n characters calls s[1:]s.substring(1) at every level, and that copies the rest of the string. How much copying does the whole run do?
Connect
- Write a recursion over a list or a string by trusting the smaller call and adding one item's work.
- Name the base case: the empty list, or a string of one character or none.
- Avoid copying the rest at every level: pass an index, so that all the calls share one list.