Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [Dynamic Programming] Fibonacci Sequence

    Published Nov 06, 2021 [  DynamicProgramming  ]

    Problem

    Write a function fib(n) that takes in a number as an argument. The function should return the n-th number of the Fibonacci sequence

    The 1st and 2nd number of the sequence is 1. To generate the next number of the sequence, we sum the previous two

    n 1 2 3 4 5 6 7 8 9
    fib(n) 1 1 2 3 5 8 13 21 24

    Brute Force Method

    
    /**
     * This is the raw implementation of fib
     *  we have base cases
     *  we reduce the problem to sub-problem & following the definition
     *
     * @param n nth fib key
     * @returns {number|*}  the value
     */
    const fibRaw = n => {
    	if (n <= 2) return 1;
    
    	return fibRaw(n - 1) + fibRaw(n - 2)
    }
    

    Call Stack for FibRaw(7)

    Call Stack for FibRaw(7)

    Complexity Analysis FibRaw

    Foo O(n) Bar O(n) Dib O(2^n) Dib O(n) Lib O(n) Fib O(2^n)

    Memoization

    const fibMemo = (n, memo = {}) => {
    	if(n in memo) return memo[n]
    	if(n <= 2) return 1
    
    	memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo)
    	return memo[n]
    }
    

    Call Stack for FibMemo(6)

    Call Stack for FibMemo(7)

    Complexity Analysis FibMemo

    FibMemo O(n)

    FibTab

    const fibTab = (n) => {
    	const table = Array(n + 1).fill(0)
    	table[1] = 1;
    
    	// each fib number contributes to next 2
    	for(let i = 0; i <= n; i++) {
    		table[i + 1] += table[i]
    		table[i + 2] += table[i]
    	}
    	return table[n]
    }
    

    fibTab

    Complexity

    • Time O(n)
    • Space O(n)

    Reference