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

Tabulation vs Memoization

Last Updated : 02 Feb, 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.

Here’s a comparison of memoization and tabulation:

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:

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);
    }
}


Python3




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);
    }
}


Python3




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

This article is contributed by Nitish Kumar.  
 



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
An array data structure is a fundamental concept in computer science that stores a collection of elements in a contiguous block of memory. It allows for efficient access to elements using indices and is widely used in programming for organizing and manipulating data. Table of Content What is an Array? Need of Array Data Structures Types of Array Da
5 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. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Stack Data Structure
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. Table of Content What is Stack D
4 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
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 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 Solve Find a peak element which is not smaller than its neighborsSolveFind the minimum and maximum element i
3 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 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 is quite high. Bubble Sort AlgorithmIn Bubble Sort algorithm,  traverse from left and compare adjacent elements and the
9 min read
Selection Sort Algorithm
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.  The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first e
9 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 work? Details of Partition Algorithm and Illustration : Illustration of QuickSort: Code impleme
14 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 +
13 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 in Linked List
Given a Linked List, the task is to insert a new node in this given Linked List at the following positions:  At the front of the linked list  After a given node.At a specific position.At the end of the linked list.Insert a Node at the Front/Beginning of Linked ListTo insert a new node at the front, we create a new node and point its next reference
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 a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output. Insertion sort is like sorting playing cards in you
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
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
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal. Example: Input: V = 5, E = 5, edges = {{1
15+ min read
Array Reverse in C/C++/Java/Python/JavaScript
Reversing an array means changing the position of each number in the array to its corresponding position from the end. For example, if a number is at position 1, its new position will be at Array.length-1, and similarly, if a number is at position 2, its new position will be at Array.length - 2, and so on. To deepen your understanding of array mani
15+ min read
Reverse a Linked List
Given a linked list, the task is to reverse the linked list by changing the links between nodes. Examples: Input: Linked List = 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; NULL Output: Reversed Linked List = 4 -&gt; 3 -&gt; 2 -&gt; 1 -&gt; NULL Input: Linked List = 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; NULL Output: Reversed Linked List = 5 -&gt; 4 -&gt; 3 -
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 :