ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Calculate Fibonacci Numbers with Memoization

Kotlin

Goal -- WPM

Ready
Exercise Algorithm Area
1package com.example.fibonacci
2
3/**
4* Calculates Fibonacci numbers using recursion with memoization.
5*
6* The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones,
7* usually starting with 0 and 1. Memoization is used to store results of expensive function calls
8* and return the cached result when the same inputs occur again.
9*/
10object FibonacciMemoized {
11
12private val memo = mutableMapOf<Int, Long>()
13
14/**
15* Computes the nth Fibonacci number.
16*
17* @param n The index of the Fibonacci number to compute (non-negative).
18* @return The nth Fibonacci number.
19* @throws IllegalArgumentException if n is negative.
20*/
21fun fib(n: Int): Long {
22if (n < 0) {
23throw IllegalArgumentException("Input must be non-negative.")
24}
25
26// Base cases
27if (n == 0) return 0L
28if (n == 1) return 1L
29
30// Check if the result is already memoized
31if (memo.containsKey(n)) {
32return memo[n]!!
33}
34
35// Compute and memoize the result
36val result = fib(n - 1) + fib(n - 2)
37memo[n] = result
38return result
39}
40
41/**
42* Example usage.
43*/
44@JvmStatic
45fun main(args: Array<String>) {
46println("Fibonacci(10): ${fib(10)}") // Expected: 55
47println("Fibonacci(20): ${fib(20)}") // Expected: 6765
48println("Fibonacci(30): ${fib(30)}") // Expected: 832040
49
50// Test edge cases
51println("Fibonacci(0): ${fib(0)}") // Expected: 0
52println("Fibonacci(1): ${fib(1)}") // Expected: 1
53try {
54fib(-5)
55} catch (e: IllegalArgumentException) {
56println("Caught expected exception for negative input: ${e.message}")
57}
58}
59}
Algorithm description viewbox

Calculate Fibonacci Numbers with Memoization

Algorithm description:

This Kotlin code calculates Fibonacci numbers efficiently using recursion combined with memoization. The Fibonacci sequence is defined by F(n) = F(n-1) + F(n-2), with base cases F(0)=0 and F(1)=1. A naive recursive implementation leads to exponential time complexity due to repeated calculations of the same subproblems. Memoization stores the results of `fib(k)` in a map, so that when `fib(k)` is called again, the stored result is returned directly, significantly improving performance. This technique is a fundamental concept in dynamic programming.

Algorithm explanation:

The `fib` function calculates the nth Fibonacci number. It first handles the base cases for n=0 and n=1. If n is negative, it throws an `IllegalArgumentException`. For positive n, it checks if the result for `n` is already present in the `memo` map. If found, it returns the cached value. Otherwise, it recursively computes `fib(n-1)` and `fib(n-2)`, sums them up, stores the result in `memo` for future use, and then returns it. The time complexity is reduced from O(2^n) to O(n) because each Fibonacci number is computed only once. The space complexity is O(n) due to the recursion depth and the memoization map storing up to n values.

Pseudocode:

Object FibonacciMemoized:
  Initialize memo as a map

  Function fib(n):
    If n < 0, throw error
    If n == 0, return 0
    If n == 1, return 1
    If n is in memo, return memo[n]
    result = fib(n - 1) + fib(n - 2)
    memo[n] = result
    Return result