Skip to content

Instantly share code, notes, and snippets.

@jadechip
Last active September 5, 2019 15:27
Show Gist options
  • Save jadechip/5aeb87ca9db07380a0fb51909272d72e to your computer and use it in GitHub Desktop.
Save jadechip/5aeb87ca9db07380a0fb51909272d72e to your computer and use it in GitHub Desktop.
Programming challenges: Nth Fibonacci
# O(n) time | O(n) space
def getNthFib(n):
memo = {1: 0, 2: 1} # start of with initial values in cache
if n in memo:
return memo[n]
else:
memo[n] = calcFib(n) # store result in cache
return memo[n]
# O(n) time | O(1) space
def calcFib(n):
# Gets called exponentially and adds the result of each call
return getNthFib(n - 1) + getNthFib(n - 2)
def getNthFib(n):
# Write your code here.
# [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
sequence = [0, 1]
if n <= 2: return sequence[n - 1]
result = 0
for idx in range(3, n + 1): # start from 3rd fibonacci number
result = sum(sequence)
sequence[0] = sequence[1]
sequence[1] = result
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment