Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions lib/fibonacci.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,40 @@
# ....
# e.g. 6th fibonacci number is 8

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n) because you execute the fib sequence n times
# Space complexity: O because no additional space is used to compute

# iterative solution
def fibonacci(n)
raise NotImplementedError
raise ArgumentError if n == nil || n < 0 || n.class != Integer
return n if n < 2

if n >= 2
current_value= 0
previous_value = 1
next_value = 0
number = n - 1

number.times do
next_value = current_value + previous_value
current_value = previous_value
previous_value = next_value
end
end

return next_value
end

# simple recursive solution
# Time complexity: exponential (O2^n) because this recursion has no memory so
# the fibonacci tree function calls base case for each branch of the tree (n-1) & (n-2),
# which grows exponentially for each subsequently higher level of the binary tree.
# Space complexity: I am not sure, but I think that it lineary because of the call stack
# required for each branch of the binary tree.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice explanations on both the iterative and recursive solutions!

def fibonacci(n)
raise ArgumentError if n == nil || n < 0 || n.class != Integer
# base case
return n if n < 2

return fibonacci(n-1) + fibonacci(n-2)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are both great solutions and very clear to read. Good work! 👍

end