Boss lesson · Unit 01
Shrink the problem
Trust the smaller call, then make it fast
What you practise
- Trust the smaller call: sum a list, reverse a string, power
- Fast power in O(log n)
Try a question from this lesson
Pick one
You must add up [4, 2, 9]. A helper has already told you that [2, 9] adds up to 11. What is left to do?
Correct answer
Add 4 to the 11
Why
That is the whole trick of recursion. Assume the smaller problem is already solved, then do the one step that turns its answer into yours. The helper is the function itself.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Trust the smaller call
To write a recursive function, do not trace every call. Decide the answer for the simplest input, then assume the function already works on a smaller input and add one step.
Here the smaller input is the list without its first number.
def add(nums):
if not nums:
return 0
return nums[0] + add(nums[1:])function add(nums) {
if (nums.length === 0) return 0;
return nums[0] + add(nums.slice(1));
}function add(nums: number[]): number {
if (nums.length === 0) return 0;
return nums[0] + add(nums.slice(1));
}Python noteAn empty list is falsy, so not nums is true exactly when the list is empty.
JavaScript noteAn empty array is truthy in JavaScript, so !nums does not work here. Compare nums.length with 0.
TypeScript noteAs in JavaScript, an empty array is truthy: test nums.length === 0, not !nums.
Concept
Halve the exponent
There is a faster way to shrink. To get b¹⁰, compute b⁵ once and square it. To get b⁵, compute b² once, square it, and multiply by b for the odd one left over.
Each call halves the exponent, so 10 is gone in a handful of steps.
2^10 = (2^5)^2
2^5 = (2^2)^2 * 2
2^2 = (2^1)^2
2^1 = (2^0)^2 * 2
2^0 = 12^10 = (2^5)^2
2^5 = (2^2)^2 * 2
2^2 = (2^1)^2
2^1 = (2^0)^2 * 2
2^0 = 12^10 = (2^5)^2
2^5 = (2^2)^2 * 2
2^2 = (2^1)^2
2^1 = (2^0)^2 * 2
2^0 = 110 more exercises in the app
- 2× fill the blanks
- 3× multiple choice
- 1× order the lines
- 3× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.