Command Palette
Search for a command to run...
Problem 12.1 · RecursionEasy
What it teaches: The same problem in three costs: exponential recursion, memoised recursion, and an O(1)-space loop.
Practise it on judges as “Fibonacci Number”.
The problem
F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2). Given n, return F(n).
Example 1
Input: n = 2
Output: 1
Example 2
Input: n = 4
Output: 3
Example 3
Input: n = 30
Output: 832040
Constraints
Pattern clues in the wording
- → Defined by a recurrence on smaller inputs
- → Overlapping subproblems (F(n − 2) is needed twice)
These clues point to Recursion: Solve the problem by solving a smaller version of it, with a base case that stops the calls.
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public int fib(int n) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | n = 2 | 1 |
| 2 | n = 4 | 3 |
| 3 | n = 0 | 0 |
+ 1 hidden test the code runner will check