diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..fddd8b6 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -1,8 +1,20 @@ # Improved Fibonacci -# Time Complexity - ? -# Space Complexity - ? (should be O(n)) +# Time Complexity - O(n) +# Space Complexity - O(n) (should be O(n)) # Hint, you may want a recursive helper method def fibonacci(n) - + return fib_helper([0, 1], 2, n) +end + +def fib_helper(solutions, current, n) + raise ArgumentError if n < 0 + return n if n == 0 || n == 1 + if current == n + return solutions[0] + solutions[1] + end + temp = solutions[0] + solutions[1] + solutions[0] = solutions[1] + solutions[1] = temp + return fib_helper(solutions, current + 1, n) end diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..0996767 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,19 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(n^2) +# Space Complexity - O(n) def super_digit(n) - + return n if n < 10 + super_digit(n.digits.sum) end - -# Time Complexity - ? -# Space Complexity - ? + def refined_super_digit(n, k) - + n = n.digits.sum * k + return refined_helper(n) end - \ No newline at end of file + +def refined_helper(n) + return n if n < 10 + super_digit(n.digits.sum) +end \ No newline at end of file