Skip to content

Instantly share code, notes, and snippets.

@BastinRobin
Last active November 18, 2019 06:24
Show Gist options
  • Select an option

  • Save BastinRobin/76c13f97ff56d2536556c8207fc76baf to your computer and use it in GitHub Desktop.

Select an option

Save BastinRobin/76c13f97ff56d2536556c8207fc76baf to your computer and use it in GitHub Desktop.
Optimal Fibonnaci
# Recursion Method
# O(2n) Time | O(n) Space Complexity
def getFib(n):
if n == 1:
return 0
if n == 2:
return 1
return getFib(n-1) + getFib(n-2)
# Recursion with cache method
# O(n) Time | O(n) Space Complexity
def getFib(n, memoize = {1:0, 2:1}):
if n in memoize:
return memoize[n]
else:
memoize[n] = getN(n-1, memoize) + getN(n-2, memoize)
return memoize[n]
# Iterative and most effective method
# O(n) Time | O(1) Space complexity
def getFib(n):
lastTwo = [0, 1]
counter = 3
while counter <= n:
nextFib = lastTwo[0] + lastTwo[1]
lastTwo[0] = lastTwo[1]
lastTwo[1] = nextFib
counter += 1
return lastTwo[1] if n > 1 else lastTwo[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment