509. Fibonacci Number
Problem Description
The Fibonacci sequence is a famous mathematical sequence where each number is the sum of the two numbers that come before it. The sequence starts with 0
and 1
.
The sequence follows this pattern:
F(0) = 0
(the first number is 0)F(1) = 1
(the second number is 1)- For any position
n > 1
:F(n) = F(n-1) + F(n-2)
For example:
F(2) = F(1) + F(0) = 1 + 0 = 1
F(3) = F(2) + F(1) = 1 + 1 = 2
F(4) = F(3) + F(2) = 2 + 1 = 3
F(5) = F(4) + F(3) = 3 + 2 = 5
The sequence continues as: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Given an integer n
, your task is to calculate and return the value of F(n)
, which is the n-th Fibonacci number in the sequence.
The solution uses an iterative approach with two variables a
and b
to track consecutive Fibonacci numbers. Starting with a = 0
and b = 1
, it performs n
iterations where in each step it updates the values by shifting: the new a
becomes the old b
, and the new b
becomes the sum of the old a
and b
. After n
iterations, variable a
holds the n-th Fibonacci number.
Intuition
The key observation is that to calculate any Fibonacci number, we only need to know the two numbers immediately before it. We don't need to store the entire sequence.
Think about how we would calculate F(5)
manually:
- Start with
F(0) = 0
andF(1) = 1
- To get
F(2)
, we add these:0 + 1 = 1
- To get
F(3)
, we needF(2) + F(1) = 1 + 1 = 2
- To get
F(4)
, we needF(3) + F(2) = 2 + 1 = 3
- To get
F(5)
, we needF(4) + F(3) = 3 + 2 = 5
Notice that at each step, we only care about the last two numbers. Once we've used F(0)
and F(1)
to get F(2)
, we never need F(0)
again. This pattern continues throughout the calculation.
This leads us to use a "sliding window" approach with just two variables. We can think of these two variables as a window that slides through the Fibonacci sequence:
- Initially:
a = 0
(representsF(0)
),b = 1
(representsF(1)
) - After 1 iteration:
a = 1
(representsF(1)
),b = 1
(representsF(2)
) - After 2 iterations:
a = 1
(representsF(2)
),b = 2
(representsF(3)
) - And so on...
The elegant part is the simultaneous assignment a, b = b, a + b
. This single line captures the essence of the Fibonacci recurrence: the current number becomes the previous number, and the next number becomes the sum of the current and previous. After n
such shifts, variable a
will contain F(n)
.
Learn more about Recursion, Memoization, Math and Dynamic Programming patterns.
Solution Approach
The solution uses an iterative approach with two variables to efficiently compute the n-th Fibonacci number.
We initialize two variables:
a = 0
- represents the current Fibonacci number in our iterationb = 1
- represents the next Fibonacci number
The core algorithm performs n
iterations. In each iteration, we update both variables simultaneously:
a, b = b, a + b
This simultaneous assignment does two things:
- Moves
b
(the next number) to becomea
(the current number) - Calculates the new next number as
a + b
and stores it inb
Let's trace through an example for n = 4
:
- Initial state:
a = 0
,b = 1
- Iteration 1:
a = 1
,b = 0 + 1 = 1
- Iteration 2:
a = 1
,b = 1 + 1 = 2
- Iteration 3:
a = 2
,b = 1 + 2 = 3
- Iteration 4:
a = 3
,b = 2 + 3 = 5
- Return
a = 3
, which isF(4)
The pattern here is that after k
iterations, a
holds F(k)
and b
holds F(k+1)
. Therefore, after n
iterations, a
contains exactly F(n)
.
This approach has a time complexity of O(n)
since we perform exactly n
iterations, and a space complexity of O(1)
as we only use two variables regardless of the input size. This is much more efficient than a recursive approach which would have O(2^n)
time complexity without memoization, or require O(n)
extra space with memoization.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through calculating F(6)
using the iterative approach with two variables.
Goal: Find the 6th Fibonacci number
Initial Setup:
a = 0
(represents F(0))b = 1
(represents F(1))- We need to perform 6 iterations
Step-by-step execution:
Iteration 1: a, b = b, a + b
- New
a
= oldb
= 1 - New
b
= olda
+ oldb
= 0 + 1 = 1 - State:
a = 1, b = 1
(nowa
holds F(1))
Iteration 2: a, b = b, a + b
- New
a
= oldb
= 1 - New
b
= olda
+ oldb
= 1 + 1 = 2 - State:
a = 1, b = 2
(nowa
holds F(2))
Iteration 3: a, b = b, a + b
- New
a
= oldb
= 2 - New
b
= olda
+ oldb
= 1 + 2 = 3 - State:
a = 2, b = 3
(nowa
holds F(3))
Iteration 4: a, b = b, a + b
- New
a
= oldb
= 3 - New
b
= olda
+ oldb
= 2 + 3 = 5 - State:
a = 3, b = 5
(nowa
holds F(4))
Iteration 5: a, b = b, a + b
- New
a
= oldb
= 5 - New
b
= olda
+ oldb
= 3 + 5 = 8 - State:
a = 5, b = 8
(nowa
holds F(5))
Iteration 6: a, b = b, a + b
- New
a
= oldb
= 8 - New
b
= olda
+ oldb
= 5 + 8 = 13 - State:
a = 8, b = 13
(nowa
holds F(6))
Result: Return a = 8
We can verify this is correct: The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, ... and F(6) = 8.
Notice how at each iteration, we're essentially sliding our two-variable window forward through the Fibonacci sequence. The variable a
always contains the Fibonacci number at position equal to the iteration count, while b
stays one step ahead, ready to help calculate the next number.
Solution Implementation
1class Solution:
2 def fib(self, n: int) -> int:
3 """
4 Calculate the nth Fibonacci number using iterative approach.
5
6 The Fibonacci sequence is defined as:
7 F(0) = 0, F(1) = 1
8 F(n) = F(n-1) + F(n-2) for n > 1
9
10 Args:
11 n: The index of the Fibonacci number to calculate (0-indexed)
12
13 Returns:
14 The nth Fibonacci number
15 """
16 # Initialize the first two Fibonacci numbers
17 # current represents F(0), next_fib represents F(1)
18 current, next_fib = 0, 1
19
20 # Iterate n times to calculate F(n)
21 # In each iteration, we shift the window forward by one position
22 for _ in range(n):
23 # Simultaneous assignment:
24 # - current becomes the previous next_fib (moving forward)
25 # - next_fib becomes the sum of current and next_fib (new Fibonacci number)
26 current, next_fib = next_fib, current + next_fib
27
28 # After n iterations, current holds the nth Fibonacci number
29 return current
30
1class Solution {
2 /**
3 * Calculates the nth Fibonacci number using iterative approach.
4 * Time Complexity: O(n)
5 * Space Complexity: O(1)
6 *
7 * @param n the position in the Fibonacci sequence (0-indexed)
8 * @return the nth Fibonacci number
9 */
10 public int fib(int n) {
11 // Initialize the first two Fibonacci numbers
12 // previous represents F(i-1), current represents F(i)
13 int previous = 0;
14 int current = 1;
15
16 // Iterate n times to compute the nth Fibonacci number
17 while (n-- > 0) {
18 // Calculate the next Fibonacci number: F(i+1) = F(i) + F(i-1)
19 int next = previous + current;
20
21 // Shift the window: move current to previous, and next to current
22 previous = current;
23 current = next;
24 }
25
26 // After n iterations, 'previous' holds the nth Fibonacci number
27 return previous;
28 }
29}
30
1class Solution {
2public:
3 int fib(int n) {
4 // Initialize the first two Fibonacci numbers
5 // prev represents F(i-1), curr represents F(i)
6 int prev = 0; // F(0) = 0
7 int curr = 1; // F(1) = 1
8
9 // Iterate n times to calculate F(n)
10 // Each iteration advances the sequence by one position
11 while (n--) {
12 // Calculate the next Fibonacci number: F(i+1) = F(i) + F(i-1)
13 int next = prev + curr;
14
15 // Shift the window forward:
16 // prev becomes the old curr (F(i-1) becomes F(i))
17 prev = curr;
18
19 // curr becomes the newly calculated next (F(i) becomes F(i+1))
20 curr = next;
21 }
22
23 // After n iterations, prev holds F(n)
24 return prev;
25 }
26};
27
1/**
2 * Calculates the nth Fibonacci number using an iterative approach
3 * @param n - The position in the Fibonacci sequence (0-indexed)
4 * @returns The nth Fibonacci number
5 */
6function fib(n: number): number {
7 // Initialize the first two Fibonacci numbers
8 // currentFib represents F(0), nextFib represents F(1)
9 let currentFib: number = 0;
10 let nextFib: number = 1;
11
12 // Iterate n times to calculate the nth Fibonacci number
13 while (n > 0) {
14 // Store the next Fibonacci number in a temporary variable
15 const tempFib: number = nextFib;
16
17 // Calculate the new next Fibonacci number by summing current and next
18 nextFib = currentFib + nextFib;
19
20 // Move forward in the sequence: current becomes the old next
21 currentFib = tempFib;
22
23 // Decrement the counter
24 n--;
25 }
26
27 // Return the nth Fibonacci number
28 return currentFib;
29}
30
Time and Space Complexity
The time complexity is O(n)
, where n
is the given integer. This is because the code uses a single for loop that iterates exactly n
times, and within each iteration, it performs constant-time operations (variable assignments).
The space complexity is O(1)
. The algorithm only uses two variables a
and b
to store intermediate Fibonacci values, regardless of the input size n
. No additional data structures or recursive call stack space is used, making the space usage constant.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Off-by-One Error in Loop Iteration Count
A common mistake is misunderstanding how many iterations are needed. Some might think we need n-1
or n+1
iterations instead of exactly n
.
Incorrect Implementation:
def fib(n: int) -> int:
a, b = 0, 1
for _ in range(n - 1): # Wrong! This would return F(n-1)
a, b = b, a + b
return a
Why it happens: Confusion about whether we're counting from 0 or 1, or whether the initial state counts as an iteration.
Solution: Remember that we start at F(0) and need exactly n
steps to reach F(n). Test with small values: for n=0, we need 0 iterations to stay at F(0)=0; for n=1, we need 1 iteration to reach F(1)=1.
2. Incorrect Variable Order in Simultaneous Assignment
The order of variables in the tuple assignment matters significantly.
Incorrect Implementation:
def fib(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = a + b, b # Wrong order! This breaks the algorithm
return a
Why it happens: Not understanding that a, b = b, a + b
evaluates the entire right side before any assignment occurs.
Solution: Always use a, b = b, a + b
where the new a
gets the old b
, and the new b
gets the sum of old a
and old b
.
3. Using Sequential Assignment Instead of Simultaneous
Attempting to update variables one at a time loses the original values needed for calculation.
Incorrect Implementation:
def fib(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a = b # Now we've lost the original value of 'a'
b = a + b # This uses the new 'a', not the original!
return a
Why it happens: Not realizing that sequential assignment changes the first variable before the second calculation.
Solution: Either use simultaneous assignment a, b = b, a + b
or store the old value in a temporary variable:
temp = a a = b b = temp + b
4. Edge Case Handling for n=0
Some implementations fail to handle the base case where n=0 correctly.
Incorrect Implementation:
def fib(n: int) -> int:
if n == 0:
return 0
a, b = 1, 1 # Starting with F(1) and F(2) instead of F(0) and F(1)
for _ in range(n - 1):
a, b = b, a + b
return a
Why it happens: Trying to optimize by handling n=0 separately but then incorrectly adjusting the starting values and iteration count.
Solution: The beauty of the original solution is that it handles n=0 naturally without special cases. Starting with a=0, b=1
and iterating exactly n
times works for all non-negative values of n.
What data structure does Breadth-first search typically uses to store intermediate states?
Recommended Readings
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Memoization Prereq Backtracking problems backtracking Memoization is a fancy word for a simple concept so is the case for a lot of things we learn in school It means saving the previous function call result in a dictionary and reading from it when we do the exact same call again
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Want a Structured Path to Master System Design Too? Donβt Miss This!