Taro Logo

Fibonacci Number

#23 Most AskedEasy
Topics:
RecursionDynamic Programming

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).

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of the input integer $n$ (e.g., is $n e 0$, and could it be very large)?
  2. Should we account for integer overflow issues if $n$ becomes large, and if so, how should large numbers be returned (e.g., using BigInt or strings)?
  3. How should the function behave if $n$ is negative or if invalid inputs are passed?
  4. Are the base cases explicitly defined as $F(0) = 0$ and $F(1) = 1$?
  5. Do you prefer an iterative approach with $O(1)$ space complexity, or is a recursive or memoized approach acceptable?

Brute Force Solution

Approach

Imagine you want to find a specific number in a growing sequence where each new value is created by adding the previous two values together. The brute force approach simply builds the sequence from the very beginning, step by step, by constantly looking backward to add the last two numbers until you reach your target position.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the sequence with the baseline starting values.
  2. To find the next value in line, look at the two values immediately preceding it and add them together.
  3. Write down this new combined value as the next step in your sequence.
  4. Repeat this exact process of looking at the last two numbers and adding them together to get the next one.
  5. Keep doing this over and over, moving forward one step at a time.
  6. Stop as soon as you have built the sequence up to the exact position you were asked to find.
  7. Take the final number you just calculated and declare that as your answer.

Code Implementation

def fibonacci_number(target_position):
    # Handle edge cases where the target position is the initial baseline values
    if target_position <= 1:
        return target_position

    sequence_list = [0, 1]

    # Iteratively build the sequence forward until we reach the target position
    for current_step in range(2, target_position + 1):
        next_sequence_value = sequence_list[-1] + sequence_list[-2]
        sequence_list.append(next_sequence_value)

    # Return the final calculated value at the exact target position
    return sequence_list[-1]

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the target position in the Fibonacci sequence we need to reach. To find the answer, a single loop iterates upward from the baseline starting values, performing a constant amount of addition work at each step. This means we perform one iteration for each step up to n. Therefore, the total operations approximate n steps, which simplifies to O(n).
Space Complexity
O(1) – The auxiliary space used by this algorithm is strictly constant because it only maintains a few individual variables to keep track of the current and previous values during the iteration. As the input size N grows, no additional data structures, auxiliary arrays, or recursive call stacks are created. Therefore, the extra memory required remains fixed at a constant size regardless of how far the sequence goes.

Optimal Solution

Approach

Instead of recalculating previous values over and over again from scratch, the optimal approach builds the sequence from the ground up by remembering previous results. By storing the last two numbers we calculated, we can quickly figure out the next one without doing repetitive work.

Here's how the algorithm would work step-by-step:

  1. Check if the target position is the very beginning, and if so, simply return that initial starting value.
  2. If we are asked for the next immediate position, return the standard second value in the sequence.
  3. Set up a method to track the two most recent numbers we have calculated so far, starting with the base values.
  4. Begin a repeating process that moves forward step by step toward the target position.
  5. At each step, add the two tracked numbers together to find the brand new value.
  6. Update our tracked numbers by letting the older one go and taking the newly found value as our latest result.
  7. Continue this steady marching forward until we reach the exact target position, and then reveal the final calculated result.

Code Implementation

def fib(target_position):
    # Base cases handle the start of the sequence without looping.
    if target_position == 0:
        return 0
    
    if target_position == 1:
        return 1
    
    previous_fibonacci = 0
    current_fibonacci = 1
    
    # Iteration computes values upwards to avoid redundant calculations.
    for step_index in range(2, target_position + 1):
        next_fibonacci = previous_fibonacci + current_fibonacci
        previous_fibonacci = current_fibonacci
        current_fibonacci = next_fibonacci
        
    # Return the final accumulated result once the target is reached.
    return current_fibonacci

Big(O) Analysis

Time Complexity
O(n) – The cost of this approach is driven by the single repeating process that marches forward step by step from the base values to the target position n. As the input size n grows, the number of addition steps increases in direct proportion because we iterate through a loop exactly n minus 1 times. This means the total operations approximate a linear progression of n steps without any nested loops or repetitive recalculations. Simplifying this linear growth yields an overall time complexity of O(n).
Space Complexity
O(1) – The algorithm tracks the sequence using a fixed number of scalar variables rather than an auxiliary array or a recursive call stack. Regardless of how large the input position N grows, we only ever store the two most recent values and a loop counter. This constant allocation of a few isolated variables means the extra memory required does not scale with N. Therefore, the overall auxiliary space complexity simplifies to O(1).

Edge Cases

Input n is 0
How to Handle:
The base case check immediately returns 0 as defined by the Fibonacci sequence.
Input n is 1
How to Handle:
The base case check correctly identifies the input and returns 1.
Negative integer inputs
How to Handle:
Throw an illegal argument exception since Fibonacci numbers are defined only for non-negative integers.
Large integer inputs exceeding standard 32-bit integer limits
How to Handle:
Use 64-bit integers or BigInteger data types to prevent numeric overflow during computation.
Repeated recursive calls for overlapping subproblems in a naive implementation
How to Handle:
Apply memoization or iterative bottom-up dynamic programming to reduce the time complexity to linear.
Deep recursion causing a stack overflow error for moderately large n
How to Handle:
Prefer an iterative approach with O(1) space complexity to avoid call stack limits entirely.
0/245 completed