Fibonacci Number - Problem
The Fibonacci sequence is one of the most famous sequences in mathematics, appearing everywhere from nature (flower petals, pine cones) to computer algorithms. Each number in the sequence is the sum of the two preceding ones.
The sequence starts with F(0) = 0 and F(1) = 1, and follows the pattern:
F(0) = 0F(1) = 1F(n) = F(n-1) + F(n-2)for n > 1
So the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
Your task: Given a non-negative integer n, calculate and return F(n) - the nth Fibonacci number.
Input & Output
example_1.py โ Basic case
$
Input:
n = 2
โบ
Output:
1
๐ก Note:
F(2) = F(1) + F(0) = 1 + 0 = 1. The sequence starts: 0, 1, 1...
example_2.py โ Mid-range case
$
Input:
n = 5
โบ
Output:
5
๐ก Note:
F(5) = F(4) + F(3) = 3 + 2 = 5. The sequence: 0, 1, 1, 2, 3, 5
example_3.py โ Edge cases
$
Input:
n = 0
โบ
Output:
0
๐ก Note:
F(0) = 0 by definition. This is the first number in the Fibonacci sequence.
Visualization
Tap to expand
Understanding the Visualization
1
Start Small
Begin with squares of size 0 and 1
2
Add Forward
Each new square = previous two combined
3
Spiral Pattern
Arrange squares to form the golden spiral
4
Optimize Memory
Only remember the last 2 square sizes
Key Takeaway
๐ฏ Key Insight: The Fibonacci sequence's beauty lies in its simplicity - each number is just the sum of the two before it. For optimal computation, we only need to remember the last two numbers, creating an elegant O(1) space solution that mimics nature's efficient patterns!
Time & Space Complexity
Time Complexity
O(n)
Single loop from 2 to n, each iteration is O(1)
โ Linear Growth
Space Complexity
O(n)
DP table stores n+1 Fibonacci numbers
โก Linearithmic Space
Constraints
- 0 โค n โค 30
- Time limit: 1 second per test case
- Space limit: O(1) preferred for optimal solution
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code