NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 70. Climbing StairsEasy
  • 7. Reverse IntegerMedium
  • 9. Palindrome NumberEasy
  • 13. Roman to IntegerEasy
  • 121. Best Time to Buy and Sell StockEasy

509. Fibonacci Number

Easy
MathDynamic ProgrammingRecursionMemoization
Answered: Mar 26, 2026
View on LeetCode

Problem Description

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Examples

Example 1

Input: n = 2
Output: 1
Explanation:
F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2

Input: n = 3
Output: 2
Explanation:
F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3

Input: n = 4
Output: 3
Explanation:
F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints

  • 0 <= n <= 30

Solutions

Complexity Analysis

Time Complexity:O(n)

We perform a single loop from 2 to n, executing a constant amount of work per iteration.

Space Complexity:O(1)

Only two variables (f0 and f1) are used regardless of input size.

This approach iteratively builds up the Fibonacci sequence by keeping track of only the last two values at each step. We initialize f0 = 0 and f1 = 1 for the base cases, then loop from 2 to n, advancing the window forward by saving f1 into a temporary variable, computing the new f1 as the sum of the previous two, and shifting f0 up. After the loop, f1 holds F(n).

Complexity Analysis

Time Complexity:O(n)

We loop from 2 to n once, doing O(1)O(1)O(1) work per step.

Space Complexity:O(1)

Only two variables are maintained at any time, with no dependency on input size.

This is the same iterative approach as Solution 1, but uses simultaneous assignment (a, b = b, a + b) to advance the two pointers in a single line, eliminating the need for a temporary variable. Starting from a = 0, b = 1, each iteration shifts a to the previous b and b to their sum, so after n - 1 iterations b holds F(n).

Complexity Analysis

Time Complexity:O(n)

Each unique value from 2 to n is computed exactly once and cached, so there are O(n)O(n)O(n) total recursive calls.

Space Complexity:O(n)

The memo dictionary stores up to n entries, and the recursion call stack reaches a depth of n.

This approach uses top-down dynamic programming: a recursive helper fib_helper computes F(n) by breaking it into F(n-1) + F(n-2), but stores each result in a memo dictionary before returning so that any subproblem is only solved once. On subsequent calls with the same n, the cached value is returned immediately, avoiding the exponential blowup of naive recursion.

Complexity Analysis

Time Complexity:O(n)

The loop runs from index 2 to n, performing O(1)O(1)O(1) work at each step.

Space Complexity:O(n)

The dp array stores n + 1 values.

This approach uses bottom-up dynamic programming by allocating an array dp of size n + 1, seeding dp[0] = 0 and dp[1] = 1, then filling each entry from index 2 to n using the recurrence dp[i] = dp[i-1] + dp[i-2]. The answer is simply dp[n] after the loop completes.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Iterative with Temporary Variable
O(n)O(n)O(n)O(1)O(1)O(1)O(1)O(1)O(1) space, easy to understand the swap logic explicitlyRequires a temporary variable; more verbose than necessary
Iterative - Pythonic Swap
O(n)O(n)O(n)O(1)O(1)O(1)Cleanest and most concise; optimal time and spaceSimultaneous assignment may be less intuitive in non-Python languages
Top-Down DP (Memoization)
O(n)O(n)O(n)O(n)O(n)O(n)Natural recursive structure mirrors the problem definitionO(n)O(n)O(n) extra space for memo dict and call stack; recursion overhead
Bottom-Up DP
O(n)O(n)O(n)O(n)O(n)O(n)Avoids recursion; straightforward DP table approachStores all n+1 values unnecessarily when only last two are needed

The optimal approach for this problem is Solution 2: Iterative - Pythonic Swap, which achieves O(n)O(n)O(n) time complexity and O(1)O(1)O(1) space complexity. It delivers the same optimal performance as Solution 1 but in a single, elegant line using simultaneous assignment, making it the most concise and idiomatic implementation.


Previous347. Top K Frequent Elements
Next746. Min Cost Climbing Stairs
Related posts
  • 70. Climbing StairsEasy
  • 7. Reverse IntegerMedium
  • 9. Palindrome NumberEasy
  • 13. Roman to IntegerEasy
  • 121. Best Time to Buy and Sell StockEasy
On this page
17 lines
1class Solution:
2 def fib(self, n: int) -> int:
3 # Base cases
4 if n <= 1:
5 return n
6
7 # Iteratively compute Fibonacci numbers up to n
8 f0, f1 = 0, 1
9
10 # Loop from 2 to n, updating f0 and f1 to hold the last two Fibonacci numbers
11 for _ in range(2, n + 1):
12 temp = f1
13 f1 = f1 + f0 # F(n) = F(n-1) + F(n-2)
14 f0 = temp # Update f0 to the previous Fibonacci number (F(n-1))
15
16 # After the loop, f1 holds the value of F(n)
17 return f1
15 lines
1class Solution:
2 def fib(self, n: int) -> int:
3 # Base cases
4 if n <= 1:
5 return n
6
7 # Iteratively compute Fibonacci numbers up to n
8 a, b = 0, 1
9
10 # Loop from 2 to n, updating a and b to hold the last two Fibonacci numbers
11 for _ in range(2, n + 1):
12 a, b = b, a + b
13
14 # After the loop, b holds the value of F(n)
15 return b
21 lines
1class Solution:
2 def fib(self, n: int) -> int:
3 # Base cases
4 if n <= 1:
5 return n
6
7 # Create a memoization dictionary to store previously computed Fibonacci numbers
8 memo = {}
9
10 def fib_helper(n):
11 # Check if the value is already computed
12 if n in memo:
13 return memo[n]
14
15 # Compute the Fibonacci number recursively and store it in the memo dictionary
16 memo[n] = fib_helper(n - 1) + fib_helper(n - 2)
17
18 return memo[n]
19
20 # Call the helper function to compute the Fibonacci number for n
21 return fib_helper(n)
17 lines
1class Solution:
2 def fib(self, n: int) -> int:
3 # Base cases
4 if n <= 1:
5 return n
6
7 # Create a dp array to store Fibonacci numbers up to n
8 dp = [0] * (n + 1)
9 dp[1] = 1
10
11 # Iteratively compute Fibonacci numbers up to n
12 for i in range(2, n + 1):
13 # The Fibonacci number at index i is the sum of the two preceding numbers
14 dp[i] = dp[i - 1] + dp[i - 2]
15
16 # After the loop, dp[n] holds the value of F(n)
17 return dp[n]