↓Skip to main content
  1. LeetCode/

LeetCode 509: Fibonacci Number

·1 min· ·
LeetCode Easy Math Dynamic-Programming Recursion Memoization
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted → Runtime Error → Accepted ×2

Approach
#

F(n) = F(n - 1) + F(n - 2) depends only on the previous two terms, so roll two variables instead of an array (Linear DP Template 1). Plain recursion without memoization is O(2^n).

My Attempts
#

A 2022-11 rewrite wrote for _ in n; an integer is not iterable (TypeError). range(n) passed.

Solution
#

class Solution:
    def fib(self, n: int) -> int:
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Loop over range(n), not for _ in n.
  • Recursion without memoization is exponential.

Interview Explanation
#

Each term depends on the previous two, so I roll two variables forward n times. Time O(n), space O(1).

Related

LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 326: Power of Three
·1 min
LeetCode Easy Math Recursion
LeetCode 326 note: divide by 3 while possible and check for 1; without loops, n is a power of three exactly when it divides 3^19
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 441: Arranging Coins
·1 min
LeetCode Easy Math Binary-Search
LeetCode 441 note: find the largest k with k(k + 1) / 2 <= n; when moving right write l = mid + 1 or the search gets stuck