C++ 0509.cpp
class Solution {
public:
int fib(int n) {
int f[50] = { 0 };
f[1] = 1;
for (int i = 2; i <= n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}
};
Difficulty
and has an acceptance rate of about 74% (4+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Math
- Memoization
- Recursion
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation computes the n-th Fibonacci number using an iterative dynamic-programming approach. A fixed-size integer array stores intermediate results, and the algorithm builds the sequence from the base cases up to the requested index. The design emphasizes simplicity and direct access to previously computed values, eliminating the overhead of recursive calls.
Key Steps
The core of the solution consists of three distinct phases: initialization of the storage structure, establishment of the base cases, and iterative construction of the sequence.
Allocation and Zero-Initialization
int f[50] = { 0 };
A stack-allocated array of length 50 is created and automatically filled with zeros. This guarantees that f[0] starts at the correct value for the Fibonacci series without requiring an explicit assignment.
Setting the First Two Values
f[1] = 1;
The second element of the array is explicitly set to one, establishing the two canonical base cases: F(0) = 0 and F(1) = 1. With these values in place, the subsequent loop can rely on them to generate higher terms.
Iterative Generation
for (int i = 2; i <= n; i++)
f[i] = f[i-1] + f[i-2];
Starting at index two, the loop computes each Fibonacci number as the sum of the two preceding entries. The loop condition i <= n ensures that the computation stops exactly at the requested index, avoiding unnecessary work.
Returning the Result
return f[n];
After the loop completes, the array entry at position n holds the desired Fibonacci number, which is returned directly to the caller.
Edge Cases Handled
When the input n equals zero, the algorithm returns f[0], which remains zero due to the initial zero-initialization of the array. For n equal to one, the explicit assignment f[1] = 1 provides the correct result without entering the loop. The fixed array size of 50 comfortably accommodates any n up to 49, ensuring that the loop never accesses out-of-bounds memory for typical problem constraints. The loop guard i <= n also prevents execution when n is less than two, thereby skipping the iterative step entirely for the smallest inputs.
Performance Optimizations Observed
The implementation avoids the exponential blow-up associated with naïve recursive Fibonacci calculations by storing each computed value exactly once. Access to previously computed terms is performed in constant time via direct array indexing, which is faster than recomputing or using more complex data structures. The use of a statically sized array eliminates dynamic memory allocation overhead, keeping the memory footprint predictable and cache-friendly. By iterating only up to the required index, the algorithm performs the minimal amount of work necessary to produce the result.
ELI5 - Simplified Explanation
Imagine you are building a tall tower out of colorful blocks. The first block is just a single one, and the second block is also just a single one. To find out how many blocks come next, you look at the two towers you just finished and stack them together to make a new one.
This code uses a special list, kind of like a row of boxes, to keep track of the height of each tower as it gets built. It starts by setting the first tower to a height of one. Then, the computer follows a rule to keep adding up the heights of the last two towers to get the height for the next one. It repeats this over and over again until it finishes building the tower at the height requested. Once the computer finishes putting all the blocks in their spot, it knows exactly how big the final tower is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | Rust | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C | ||||||||||||
| lkwq007 | Python | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Java | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C | ||||||||||||
| lkwq007 | Python | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Java | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 70: Climbing Stairs
- problem 842: Split Array into Fibonacci Sequence
- problem 873: Length of Longest Fibonacci Subsequence
- problem 1137: N-th Tribonacci Number
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality