Memoized Function - Problem

Implement a function with memoization to efficiently calculate the Nth Fibonacci number.

The Fibonacci sequence is defined as:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

Your function should use memoization to store previously calculated values and avoid redundant computations.

Input: An integer n (0 ≤ n ≤ 100)

Output: The Nth Fibonacci number

Input & Output

Example 1 — Small Number
$ Input: n = 5
Output: 5
💡 Note: F(5) = F(4) + F(3) = 3 + 2 = 5. The sequence is: 0, 1, 1, 2, 3, 5
Example 2 — Base Case
$ Input: n = 0
Output: 0
💡 Note: F(0) = 0 by definition
Example 3 — Another Base Case
$ Input: n = 1
Output: 1
💡 Note: F(1) = 1 by definition

Constraints

  • 0 ≤ n ≤ 100
  • Result fits in 64-bit integer

Visualization

Tap to expand
INPUTALGORITHMRESULTInputn = 5Find 5th Fibonacci numberF(5) = F(4) + F(3)1Check Cache2Calculate Missing3Store in Cache4Return ResultCacheF(0)=0, F(1)=1F(2)=1, F(3)=2F(4)=3, F(5)=5Output5F(5) = 5Sequence: 0,1,1,2,3,5-->-->Key Insight:Memoization transforms O(2^n) exponential recursion into O(n) linear timeby caching intermediate results and avoiding redundant calculations.TutorialsPoint - Memoized Function | Top-Down Memoization
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen