The Wayback Machine - https://web.archive.org/web/20241128125508/https://www.geeksforgeeks.org/tabulation-vs-memoization/
Open In App

Tabulation vs Memoization

Last Updated : 26 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Tabulation and memoization are two techniques used in dynamic programming to optimize the execution of a function that has repeated and expensive computations. Although both techniques have similar goals, there are some differences between them.

Memoization is a top-down approach where we cache the results of function calls and return the cached result if the function is called again with the same inputs. It is used when we can divide the problem into subproblems and the subproblems have overlapping subproblems. Memoization is typically implemented using recursion and is well-suited for problems that have a relatively small set of inputs.

Tabulation is a bottom-up approach where we store the results of the subproblems in a table and use these results to solve larger subproblems until we solve the entire problem. It is used when we can define the problem as a sequence of subproblems and the subproblems do not overlap. Tabulation is typically implemented using iteration and is well-suited for problems that have a large set of inputs.

Memoization:

Top-down approach
Caches the results of function calls
Recursive implementation
Well-suited for problems with a relatively small set of inputs
Used when the subproblems have overlapping subproblems

Tabulation:

Bottom-up approach
Stores the results of subproblems in a table
Iterative implementation
Well-suited for problems with a large set of inputs
Used when the subproblems do not overlap
Here’s an example of using memoization and tabulation to solve the same problem – calculating the nth number in the Fibonacci sequence:


Types of the approach of dynamic programming algorithm

Memoization implementation:

C++
#include <iostream>
#include <unordered_map>

int fibonacci(int n, std::unordered_map<int, int>& cache) {
    if (cache.find(n) != cache.end()) {
        return cache[n];
    }
    int result;
    if (n == 0) {
        result = 0;
    } else if (n == 1) {
        result = 1;
    } else {
        result = fibonacci(n-1, cache) + fibonacci(n-2, cache);
    }
    cache[n] = result;
    return result;
}
Java
import java.util.HashMap;
import java.util.Map;

public class Fibonacci {

    public static int fibonacci(int n, Map<Integer, Integer> cache) {
        if (cache.containsKey(n)) {
            return cache.get(n);
        }

        int result;
        if (n == 0) {
            result = 0;
        } else if (n == 1) {
            result = 1;
        } else {
            result = fibonacci(n - 1, cache) + fibonacci(n - 2, cache);
        }

        cache.put(n, result);
        return result;
    }

    public static void main(String[] args) {
        int n = 6;  // Find the 6th Fibonacci number
        Map<Integer, Integer> cache = new HashMap<>();
        int result = fibonacci(n, cache);
        System.out.println("The " + n + "th Fibonacci number is: " + result);
    }
}
Python
def fibonacci(n, cache={}):
    if n in cache:
        return cache[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = 1
    else:
        result = fibonacci(n-1) + fibonacci(n-2)
    cache[n] = result
    return result
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to calculate Fibonacci numbers with memoization
    static int Fibonacci(int n, Dictionary<int, int> cache)
    {
        if (cache.ContainsKey(n))
        {
            return cache[n];
        }

        int result;
        if (n == 0)
        {
            result = 0;
        }
        else if (n == 1)
        {
            result = 1;
        }
        else
        {
            result = Fibonacci(n - 1, cache) + Fibonacci(n - 2, cache);
        }

        cache[n] = result;
        return result;
    }

    static void Main()
    {
        int n = 10; // Change n to the desired Fibonacci number

        Dictionary<int, int> cache = new Dictionary<int, int>();

        // Calculate and print the Fibonacci number
        int result = Fibonacci(n, cache);
        Console.WriteLine($"Fibonacci({n}) = {result}");
    }
}
JavaScript
// Define a JavaScript object (equivalent to an unordered_map in C++) to store cached Fibonacci values
const cache = new Map();

// Function to calculate the nth Fibonacci number using memoization
function fibonacci(n) {
    // If the result for 'n' is already in the cache, return it
    if (cache.has(n)) {
        return cache.get(n);
    }

    let result;
    // Base cases
    if (n === 0) {
        result = 0;
    } else if (n === 1) {
        result = 1;
    } else {
        // Recursively calculate Fibonacci(n-1) and Fibonacci(n-2) and store the result
        result = fibonacci(n - 1) + fibonacci(n - 2);
    }

    // Cache the result for future use
    cache.set(n, result);
    return result;
}

// Example usage:
const n = 10; // Replace with the desired value of 'n'
const result = fibonacci(n);
console.log(`Fibonacci(${n}) = ${result}`);

Output
 

Tabulation implementation:

C++
#include <iostream>
#include <vector>

int fibonacci(int n)
{
    if (n == 0) {
        return 0;
    }
    else if (n == 1) {
        return 1;
    }
    else {
        std::vector<int> table(n + 1, 0);
        table[0] = 0;
        table[1] = 1;
        for (int i = 2; i <= n; i++) {
            table[i] = table[i - 1] + table[i - 2];
        }
        return table[n];
    }
}
Java
import java.util.Arrays;

public class Fibonacci {

    public static int fibonacci(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return 1;
        } else {
            int[] table = new int[n + 1];
            table[0] = 0;
            table[1] = 1;
            for (int i = 2; i <= n; i++) {
                table[i] = table[i - 1] + table[i - 2];
            }
            return table[n];
        }
    }

    public static void main(String[] args) {
        int n = 6;  // Find the 6th Fibonacci number
        int result = fibonacci(n);
        System.out.println("The " + n + "th Fibonacci number is: " + result);
    }
}
Python
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        table = [0] * (n + 1)
        table[0] = 0
        table[1] = 1
        for i in range(2, n+1):
            table[i] = table[i-1] + table[i-2]
        return table[n]
C#
using System;

class Fibonacci
{
    public static int CalculateFibonacci(int n)
    {
        if (n == 0)
        {
            return 0;
        }
        else if (n == 1)
        {
            return 1;
        }
        else
        {
            int[] table = new int[n + 1];
            table[0] = 0;
            table[1] = 1;

            for (int i = 2; i <= n; i++)
            {
                table[i] = table[i - 1] + table[i - 2];
            }

            return table[n];
        }
    }

    static void Main()
    {
        int n = 6;  // Find the 6th Fibonacci number
        int result = CalculateFibonacci(n);
        Console.WriteLine($"The {n}th Fibonacci number is: {result}");
    }
}
JavaScript
function fibonacci(n) {
  if (n === 0) {
    return 0;
  } else if (n === 1) {
    return 1;
  } else {
    let table = Array(n + 1).fill(0);
    table[0] = 0;
    table[1] = 1;
    for (let i = 2; i <= n; i++) {
      table[i] = table[i - 1] + table[i - 2];
    }
    return table[n];
  }
}

Output
 

In the memoization implementation, we use a dictionary object called cache to store the results of function calls, and we use recursion to compute the results.

In the tabulation implementation, we use an array called table to store the results of subproblems, and we use iteration to compute the results.

Both implementations achieve the same result, but the approach used is different. Memoization is a top-down approach that uses recursion, while tabulation is a bottom-up approach that uses iteration.

Prerequisite – Dynamic Programming, How to solve Dynamic Programming problems? 
There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problems: 

  1. Tabulation: Bottom Up
  2. Memoization: Top Down

Before getting to the definitions of the above two terms consider the following statements: 

  • Version 1: I will study the theory of DP from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master DP.
  • Version 2: To Master DP, I would have to practice Dynamic problems and practice problems – Firstly, I would have to study some theories of DP from GeeksforGeeks

Both versions say the same thing, the difference simply lies in the way of conveying the message and that’s exactly what Bottom-Up and Top-Down DP do. Version 1 can be related to Bottom-Up DP and Version-2 can be related as Top-Down DP. 
 

Tabulation Method – Bottom Up Dynamic Programming 


As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition. 
Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So,  we need to find the value of destination state i.e dp[n]. 
If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state. 
Now, Why do we call it the tabulation method? 
To know this let’s first write some code to calculate the factorial of a number using a bottom-up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x. 
Now, it is quite obvious that dp[x+1] = dp[x] * (x+1) 
 

// Tabulated version to find factorial x.
int dp[MAXN];
// base case
int dp[0] = 1;
for (int i = 1; i< =n; i++)
{
dp[i] = dp[i-1] * i;
}


The above code clearly follows the bottom-up approach as it starts its transition from the bottom-most base case dp[0] and reaches its destination state dp[n]. Here, we may notice that the DP table is being populated sequentially and we are directly accessing the calculated states from the table itself and hence, we call it the tabulation method. 
 

Memoization Method – Top-Down Dynamic Programming 


Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP. 
Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state. 
Once again, let’s write the code for the factorial problem in the top-down fashion 
 

// Memoized version to find factorial x.
// To speed up we store the values
// of calculated states
// initialized to -1
int dp[MAXN]
// return fact x!
int solve(int x)
{
if (x==0)
return 1;
if (dp[x]!=-1)
return dp[x];
return (dp[x] = x * solve(x-1));
}


As we can see we are storing the most recent cache up to a limit so that if next time we got a call from the same state we simply return it from the memory. So, this is why we call it memoization as we are storing the most recent state values. 
In this case, the memory layout is linear that’s why it may seem that the memory is being filled in a sequential manner like the tabulation method, but you may consider any other top-down DP having 2D memory layout like Min Cost Path, here the memory is not filled in a sequential manner. 
 

Tabulation vs Memoization:

    Tabulation      Memoization   
StateState transition relation is difficult to thinkState Transition relation is easy to think
CodeCode gets complicated when a lot of 
conditions are required
Code is easy and less complicated
 
SpeedFast, as we directly access previous states from the tableSlow due to a lot of recursive calls and return statements
Subproblem solvingIf all subproblems must be solved at least once, a bottom-up dynamic programming algorithm usually outperforms a top-down memoized algorithm by a constant factorIf some subproblems in the subproblem space need not be solved at all, the memoized solution has the advantage of solving only those subproblems that are definitely required 
Table entriesIn the Tabulated version, starting from the first entry, all entries are filled one by oneUnlike the Tabulated version, all entries of the lookup table are not necessarily filled in Memoized version. The table is filled on demand.
ApproachGenerally, tabulation(dynamic programming) is an iterative approachOn the other hand, memoization is a recursive approach.
 


Previous Article
Next Article

Similar Reads

Meanings and objectives of Tabulation
Tabulation is a fundamental concept in Dynamic programming (DP), which entails dividing a problem into smaller subproblems and an array to hold the outcomes of these subproblems. What is Tabulation?One of the two primary methodologies in dynamic programming is tabulation, and memoization serves as the other. Tabulation creates a table (often an arr
5 min read
Edit Distance | DP using Memoization
Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert 'str1' into 'str2'. InsertRemoveReplace All of the above operations are of equal cost. Examples: Input: str1 = "geek", str2 = "gesek" Output: 1 We can convert str1 into str2 by inserting a 's'. Input:
15+ min read
Memoization (1D, 2D and 3D)
Most of the Dynamic Programming problems are solved in two ways: Tabulation: Bottom UpMemoization: Top Down One of the easier approaches to solve most of the problems in DP is to write the recursive code at first and then write the Bottom-up Tabulation Method or Top-down Memoization of the recursive function. The steps to write the DP solution of T
15+ min read
Water Jug Problem using Memoization
Given two jugs with the maximum capacity of m and n liters respectively. The jugs don't have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or (d, 0). Examples: Input: 4 3 2 Output: (0, 0) --
9 min read
Longest Common Subsequence | DP using Memoization
Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them. Examples: Input: s1 = “ABCDGH”, s2 = “AEDFHR” Output: 3 LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. Input: s1 = “striver”, s2 = “raj” Output: 1 The naive solution for this problem is to generate all subseq
13 min read
Array Data Structure Guide
In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive( at contiguous locations. It offers mainly the following advantag
4 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Here’s the comparison of Linked List vs Arrays Linked List: Data Structure: Non-contiguous Memory Allocation:
3 min read
Binary Search Tree
A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the parent node.
3 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. Sorting is provided in library implementation of most of the programming languages. Basics of Sorting Algorithms:Introduction to Sorting Applications of Sorting Sorting Algorithms:Comparison Based : Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Quick
3 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
5 min read
DSA Tutorial - Learn Data Structures and Algorithms
Data Structures and Algorithms (DSA) refer to the study of data structures used for organizing and storing data, along with the design of algorithms for solving problems that operate on these data structures. Why to Learn DSA?Whether it’s finding the shortest path in a GPS system or optimizing search results in a search engine, DSA plays an importa
8 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of the node. The AVL tree is named after its inventors, Georgy
3 min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. Level 1Problems Practice Find the Minimum and Maximum Element in an Array Solve Array Reverse Solve Write a Program to Cyclic
3 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS stands for Depth First Search.Data StructureBFS(Brea
2 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
11 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we can quickly find and move t
15 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Prim’s Algorithm for Minimum Spanning Tree (MST)
Introduction to Prim's algorithm:We have discussed Kruskal's algorithm for Minimum Spanning Tree. Like Kruskal's algorithm, Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an
15+ min read
Kruskal’s Minimum Spanning Tree (MST) Algorithm
A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. To learn more about Minimum Spanning Tree, refer to this article. Introduction to Kruskal's Algorithm:Here we will discuss Kruskal's algorithm to fi
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Depth First Search or DFS for a Graph
Depth First Search (or DFS) for a graph is similar to Depth First Traversal of a tree. Like trees, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. After we finish traversing one adjacent vertex and its reachable vertices, we
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read
Maximum Subarray Sum - Kadane's Algorithm
Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -4}Output: -2Explanation: The subarray {-2} has the largest sum -2. Input: arr[] = {5, 4, 1, 7, 8}Output: 25
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg