bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 509. Fibonacci Number

509. Fibonacci Number

Leetcode Solutions

Iterative Bottom-Up Approach

  1. Check if n is 0 or 1, return n as it is the base case.
  2. Initialize two variables, prev1 and prev2, to represent the last two Fibonacci numbers. Initially, prev1 is set to 1 and prev2 to 0.
  3. Loop from 2 to n, and for each iteration: a. Calculate the current Fibonacci number as the sum of prev1 and prev2. b. Update prev2 to the value of prev1. c. Update prev1 to the value of the current Fibonacci number.
  4. After the loop ends, return prev1 which now holds the value of F(n).
UML Thumbnail

Recursive Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR