CP

509. Fibonacci Number

MetricComplexityReason
Time ComplexityO(n)O(n)Each subproblem computed once
Space ComplexityO(n)O(n)Cache storage and recursion stack
class Solution:
    @cache
    def fib(self, n: int) -> int:
        if n <= 1:
            return n
        return self.fib(n - 1) + self.fib(n - 2)
MetricComplexityReason
Time ComplexityO(n)O(n)Single loop from 2 to n
Space ComplexityO(1)O(1)Only constant variables
class Solution:
    def fib(self, n: int) -> int:
        if n <= 1:
            return n

        prepre, pre = 0, 1

        for i in range(2, n):
            cur = prepre + pre
            prepre = pre
            pre = cur

        return prepre + pre
MetricComplexityReason
Time ComplexityO(1)O(1)Direct formula (Binet's)
Space ComplexityO(1)O(1)Only constant variables
class Solution:
    def fib(self, n: int) -> int:
        phi = (1 + 5 ** 0.5) / 2
        return int(round(phi ** n) / 5 ** 0.5)

See Binet's Formula