Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Iterative and Recursive Fibonacci with Memoization

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Iterative and Recursive Fibonacci with Memoization. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

For a numerical utility used in Metron coding workflows, implement Fibonacci number calculation using three approaches: an iterative algorithm, a direct recursive algorithm, and a recursive algorithm with memoization.

Define F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n >= 2. Implement one function that accepts a non-negative integer n and a method name, then returns the corresponding Fibonacci value.

Formal Specification

Implement fibonacci(n, method), where n is an integer and method is one of "iterative", "recursive", or "memoized". Return an integer containing F(n). For valid inputs, all three methods must return the same value.

The recursive method may use the direct exponential recurrence and is intended for smaller inputs. The iterative and memoized methods must support the largest permitted input efficiently.

Constraints

  • 0 <= n <= 30 for method = "recursive"
  • 0 <= n <= 100000 for method = "iterative" or "memoized"
  • method is one of "iterative", "recursive", or "memoized"
  • Return the exact Fibonacci value using Python integers

Function Signature

def fibonacci(n, method):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output