Skip to content
LEETFLIX

Easy · Fibonacci roll. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 509. Fibonacci Number. The copyrighted prompt is on LeetCode. This page is a working Fibonacci roll for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

n =
2

Output

1

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Two rolling variables

F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2). Roll a pair forward n times.

You only need the last two values. Recursing from the top would recompute the same suffixes.

Algorithm

  1. If n < 2, return n.
  2. a, b = 0, 1; then a, b = b, a+b for n-1 steps.
  3. Return b.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def fib(self, n: int) -> int:        if n < 2:            return n        a, b = 0, 1        for _ in range(2, n + 1):            a, b = b, a + b        return b
Watch this run

03

Interactive walkthrough

Playing “Two rolling variables”. Edit the input, hit Run, then scrub.

Approach: Two rolling variables

Loading animation…