Fibonacci Number - Complete Solution Guide
Fibonacci Number is LeetCode problem 509, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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
Detailed Explanation
The problem asks us to calculate the nth Fibonacci number. The Fibonacci sequence starts with 0 and 1. Each subsequent number is the sum of the two preceding numbers. Given an integer 'n', we need to return the nth Fibonacci number (F(n)). The constraints are 0 <= n <= 30.
Solution Approach
The provided code uses an iterative approach with constant space to calculate the nth Fibonacci number. It initializes two variables, 'a' and 'b', to represent the two preceding Fibonacci numbers. It then iterates from 2 to n, updating 'a' and 'b' in each iteration to represent the next Fibonacci number in the sequence. The final value of 'b' after the loop is the nth Fibonacci number.
Step-by-Step Algorithm
- Step 1: Handle the base cases: If n is 0 or 1, return n directly.
- Step 2: Initialize two variables, 'a' to 0 and 'b' to 1. These will hold F(n-2) and F(n-1) respectively.
- Step 3: Iterate from i = 2 to n. In each iteration:
- Step 4: Calculate the next Fibonacci number (F(i)) as the sum of 'a' and 'b'.
- Step 5: Update 'a' to the value of 'b', and 'b' to the calculated sum.
- Step 6: After the loop finishes, return the value of 'b', which now holds F(n).
Key Insights
- Insight 1: The Fibonacci sequence is defined recursively, but a simple iterative approach is more efficient.
- Insight 2: We only need to keep track of the last two Fibonacci numbers to compute the next one, making space optimization possible.
- Insight 3: The base cases F(0) = 0 and F(1) = 1 are critical for the sequence to start correctly.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Math, Dynamic Programming, Recursion, Memoization.
Companies
Asked at: Accenture, Capgemini, Cognizant, EY, Infosys, J.P. Morgan, Nvidia, SAP, Zoox, tcs.