From 0a133dbf237934fb65edcc44024f7117a7701340 Mon Sep 17 00:00:00 2001 From: Hana Date: Mon, 15 Apr 2019 18:43:56 -0700 Subject: [PATCH 1/2] Fibonacci passing all tests --- lib/fibonacci.rb | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 606755b..776c4cc 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -5,8 +5,21 @@ # .... # e.g. 6th fibonacci number is 8 -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), where n is the the number of values in the array +# Space complexity: O(n), where n is the number of values in the array def fibonacci(n) - raise NotImplementedError + if n == nil || n < 0 + raise ArgumentError, "Invalid input for n, #{n}" + elsif n == 0 || n == 1 + return n + else + array = [0, 1] + + (n-2).times do + num = array[-1] + array[-2] + array << num + end + + return array[n] + end end From 516eb0a027960a431f73df1408a3a0472320b1a4 Mon Sep 17 00:00:00 2001 From: Hana Date: Thu, 18 Apr 2019 18:30:44 -0700 Subject: [PATCH 2/2] rewrite for better space complexity --- lib/fibonacci.rb | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 776c4cc..a273e76 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -6,20 +6,24 @@ # e.g. 6th fibonacci number is 8 # Time complexity: O(n), where n is the the number of values in the array -# Space complexity: O(n), where n is the number of values in the array +# Space complexity: O(c), where c is the integers that are being rewritten + def fibonacci(n) if n == nil || n < 0 raise ArgumentError, "Invalid input for n, #{n}" elsif n == 0 || n == 1 return n else - array = [0, 1] + fib_num_prev = 0 # 2 + fib_num_curr = 1 # 3 + fib_num_next = 0 # 3 - (n-2).times do - num = array[-1] + array[-2] - array << num + (n-1).times do + fib_num_next = fib_num_prev + fib_num_curr + fib_num_prev = fib_num_curr + fib_num_curr = fib_num_next end - return array[n] + return fib_num_next end -end +end \ No newline at end of file