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) = 0
  • F(1) = 1
  • F(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
๐ŸŒ€ Fibonacci Golden Spiral0112358Golden Ratioฯ† โ‰ˆ 1.618๐Ÿ”‘ Key Insights:โ€ข Each Fibonacci number = sum of previous two numbersโ€ข Ratio between consecutive Fibonacci numbers approaches Golden Ratio (ฯ†)โ€ข Space-optimized solution: only track last two values
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

DP table stores n+1 Fibonacci numbers

n
2n
โšก Linearithmic Space

Constraints

  • 0 โ‰ค n โ‰ค 30
  • Time limit: 1 second per test case
  • Space limit: O(1) preferred for optimal solution
Asked in
Amazon 45 Google 35 Microsoft 28 Apple 22
85.4K Views
High Frequency
~12 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen