WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Recursion and Dynamic Programming Problems Β· question 80 of 120

Can you implement a function to compute the nth number in the Fibonacci sequence using dynamic programming?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

Computing the nth Fibonacci number using dynamic programming is pretty straightforward, you just need to store each Fibonacci number as you compute it and use previously computed numbers to compute the next ones.

Here is a simple Python implementation:

def fib(n):
    F = [0, 1] + [0]*(n-1)
    for i in range(2, n+1):
        F[i] = F[i-1] + F[i-2]
    return F[n]

This function creates an empty list β€˜Fβ€˜ of size β€˜n+1β€˜ and initializes β€˜F[0]β€˜ and β€˜F[1]β€˜ to β€˜0β€˜ and β€˜1β€˜ respectively. After that, it computes each β€˜F[i]β€˜ as β€˜F[i-1] + F[i-2]β€˜ for β€˜i = 2β€˜ to β€˜nβ€˜.

This approach allows it to calculate the nth Fibonacci number in O(n) time, which is much better than the naive recursive solution that takes O(2n) time.

We can also optimize this function by only keeping the last two previously computed Fibonacci numbers:

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a+b
    return a

This version of the function computes the nth Fibonacci number in O(n) time and O(1) space.

If you’re interested in mathematical representations, here’s a brief overview:

The Fibonacci sequence is formally defined by the recurrence relation:

β€˜F(n) = F(n-1) + F(n-2)β€˜

with β€˜F(0) = 0β€˜ and β€˜F(1) = 1β€˜. Hence, the formula used in the dynamic programming-based implementations is β€˜F[i] = F[i-1] + F[i-2]β€˜ for β€˜i = 2β€˜ to β€˜nβ€˜.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics