Skip to content

Files

Latest commit

dacbc1a · Mar 1, 2023

History

History
This branch is 2 commits ahead of, 16 commits behind igorwojda/kotlin-coding-challenges:main.

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Feb 7, 2023
Feb 7, 2023
Mar 1, 2023

Recursive cache fibonacci

Instructions

Below function returns out the n-th entry in the fibonacci series.

private fun fibonacciSequenceRecursiveCached(n: Int): Int {
    if (n < 2) {
        return n
    }

    return fibonacciSequenceRecursiveCached(n - 1) + fibonacciSequenceRecursiveCached(n - 2)
}

However due to recursion this function has exponential complexity (function is called recursively multiple times with identical arguments), so its execution takes a long time. Store arguments of each call along with the result using MethodCache class.

private data class MethodCache(val n: Int, val result: Int)

If the function is called again with the same arguments, return the precomputed result rather than running the function again.

Challenge | Solution