The Wayback Machine - https://web.archive.org/web/20240829164319/https://www.geeksforgeeks.org/what-is-memoization-a-complete-tutorial/
Open In App

What is memoization? A Complete tutorial

Last Updated : 10 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The term “Memoization” comes from the Latin word “memorandum” (to remember), which is commonly shortened to “memo” in American English, and which means “to transform the results of a function into something to remember.”.

In computing, memoization is used to speed up computer programs by eliminating the repetitive computation of results, and by avoiding repeated calls to functions that process the same input.

What is memoization

What is memoization

Table of Contents

   

Why is Memoization used?

Memoization is a specific form of caching that is used in dynamic programming. The purpose of caching is to improve the performance of our programs and keep data accessible that can be used later. It basically stores the previously calculated result of the subproblem and uses the stored result for the same subproblem. This removes the extra effort to calculate again and again for the same problem. And we already know that if the same problem occurs again and again, then that problem is recursive in nature.

Where to use Memoization?

We can use the memoization technique where the use of the previously-calculated results comes into the picture. This kind of problem is mostly used in the context of recursion, especially with problems that involve overlapping subproblems.

Let’s take an example where the same subproblem repeats again and again. 

Example to show where to use memoization: 

Let us try to find the factorial of a number.

Below is a recursive method for finding the factorial of a number:

int factorial(unsigned int n)
{
   if (n == 0)
       return 1;
   return n * factorial(n – 1);
}

What happens if we use this recursive method?

If you write the complete code for the above snippet, you will notice that there will be 2 methods in the code:

1. factorial(n)
2. main()

Now if we have multiple queries to find the factorial, such as finding factorial of 2, 3, 9, and 5, then we will need to call the factorial() method 4 times:

factorial(2)
factorial(3)
factorial(9)
factorial(5)
Recursive method to find Factorial

Recursive method to find Factorial

So it is safe to say that for finding factorial of numbers K numbers, the time complexity needed will be O(N*K)

  • O(N) to find the factorial of a particular number, and
  • O(K) to call the factorial() method K different times.

How Memoization can help with such problems?

If we notice in the above problem, while calculation factorial of 9: 

  • We are calculating the factorial of 2
  • We are also calculating the factorial of 3,
  • and We are calculating the factorial of 5 as well

Therefore if we store the result of each individual factorial at the first time of calculation, we can easily return the factorial of any required number in just O(1) time. This process is known as Memoization. 

Solution using Memoization (How does memoization work?):

If we find the factorial of 9 first and store the results of individual sub-problems, we can easily print the factorial of each input in O(1).

Therefore the time complexity to find factorial numbers using memoization will be O(N)

  • O(N) to find the factorial of the largest input
  • O(1) to print the factorial of each input.

Types of Memoization

The Implementation of memoization depends upon the changing parameters that are responsible for solving the problem. There are various dimensions of caching that are used in memoization technique, Below are some of them:

  • 1D Memoization: The recursive function that has only one argument whose value was not constant after every function call.
  • 2D Memoization: The recursive function that has only two arguments whose value was not constant after every function call.
  • 3D Memoization:  The recursive function that has only three arguments whose values were not constant after every function call.

How Memoization technique is used in Dynamic Programming?

Dynamic programming helps to efficiently solve problems that have overlapping subproblems and optimal substructure properties. The idea behind dynamic programming is to break the problem into smaller sub-problems and save the result for future use, thus eliminating the need to compute the result repeatedly.

There are two approaches to formulate a dynamic programming solution:

  1. Top-Down Approach:  This approach follows the memoization technique. It consists of recursion and caching. In computation, recursion represents the process of calling functions repeatedly, whereas cache refers to the process of storing intermediate results.
  2. Bottom-Up Approach: This approach uses the tabulation technique to implement the dynamic programming solution. It addresses the same problems as before, but without recursion. In this approach, iteration replaces recursion. Hence, there is no stack overflow error or overhead of recursive procedures.
How Memoization technique is used in Dynamic Programming

How Memoization technique is used in Dynamic Programming

How Memoization is different from Tabulation?

Tabulation vs Memoization

Tabulation vs Memoization

For more details please refer: Tabulation vs. Memoization

Coding Practice Problems on Memoization

Question

Article

Practice

Video

Count ways to reach the n’th stair

View Solve

Watch

Word Break Problem | DP-32

View Solve Watch

Program for Fibonacci numbers

View Solve Watch

nth Catalan Number

View Solve

Watch

Gold Mine Problem

View Solve

Watch

Subset Sum Problem

View Solve

Watch

Cutting a Rod

View Solve Watch

Min Cost Path

View Solve

Watch

Minimum number of jumps to reach end

View Solve

Watch

Longest Palindromic Substring | Set 1

View Solve Watch

Longest Repeating Subsequence

View Solve Watch

Count ways to reach the nth stair using step 1, 2 or 3

View Solve Watch

Count of different ways to express N as the sum of 1, 3 and 4

View Solve Watch

Count number of ways to cover a distance

View Solve Watch

Count of arrays having consecutive element with different values

View Solve

Watch

Largest Sum Contiguous Subarray

View Solve Watch

Smallest sum contiguous subarray

View Solve

Watch

Unique paths in a Grid with Obstacles

View Solve Watch

Different ways to sum n using numbers greater than or equal to m

View Solve

Watch

Frequently asked questions (FAQs) about Memoization

1: Is memoization better than DP?

Memoization is the top-down approach to solving a problem with dynamic programming. It’s called memoization because we will create a memo for the values returned from solving each problem.

2: Is memoization the same as caching?

Memoization is actually a specific type of caching. The term caching can generally refer to any storing technique (like HTTP caching) for future use, but memoizing refers more specifically to caching function that returns the value.

3: Why memoization is top-down?

The top-Down approach breaks the large problem into multiple subproblems. if the subproblem is solved already then reuse the answer. Otherwise, Solve the subproblem and store the result in some memory.

4: Does memoization use recursion?

Memoization follows top-down approach to solving the problem. It consists of recursion and caching. In computation, recursion represents the process of calling functions repeatedly, whereas cache refers to the process of storing intermediate results.

5: Should I use tabulation or memoization?

For problems requiring all subproblems to be solved, tabulation typically outperforms memoization by a constant factor. This is because the tabulation has no overhead of recursion which reduces the time for resolving the recursion call stack from the stack memory.
Whenever a subproblem needs to be solved for the original problem to be solved, memoization is preferable since a subproblem is solved lazily, i.e. only the computations that are required are carried out.

6: Where is memoization used?

Memoization is an optimization technique used to speed up computer programs by caching the results of expensive function calls and returning them when the same inputs are encountered again.

7: Why is it called memoization?

The term “memoization” comes from the Latin word “memorandum” (“to remember”), which is commonly shortened to “memo” in American English, and which means “to transform the results of a function into something to remember.”.

8: How does memoization reduce time complexity?

Solving the same problem again and again takes time and increases the run-time complexity of the overall program. This problem can be resolved by maintaining some cache or memory where we will store the already calculated result of the problem for some particular input. So that if we don’t want to recalculate the same problem, we can simply use the result that is stored in the memory and reduce the time complexity.

9: What is the difference between memoization and caching?

Memoization is actually a specific type of caching that involves caching the return value of a function based on input. Caching is a more general term. For example, HTTP caching is caching but it is not memoization.

10: Why tabulation is faster than memoization?

Tabulation is usually faster than memoization, because it is iterative and solving subproblems requires no overhead of recursive calls.

Memoization is a technique used in computer science to speed up the execution of recursive or computationally expensive functions by caching the results of function calls and returning the cached results when the same inputs occur again.

The basic idea of memoization is to store the output of a function for a given set of inputs and return the cached result if the function is called again with the same inputs. This technique can save computation time, especially for functions that are called frequently or have a high time complexity.

Here’s a step-by-step guide to implementing memoization:

Identify the function that you want to optimize using memoization. This function should have repeated and expensive computations for the same input.

Create a dictionary object to store the cached results of the function. The keys of the dictionary should be the input parameters to the function, and the values should be the computed results.

At the beginning of the function, check if the input parameters are already present in the cache dictionary. If they are, return the cached result.

If the input parameters are not in the cache dictionary, compute the result and store it in the cache dictionary with the input parameters as the key.

Return the computed result.

Here’s a Python code example of implementing memoization using a dictionary:

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


Output

 

In the above code, we define a function called fibonacci that calculates the nth number in the Fibonacci sequence. We use a dictionary object called cache to store the results of the function calls. If the input parameter n is already present in the cache dictionary, we return the cached result. Otherwise, we compute the result using recursive calls to the fibonacci function and store it in the cache dictionary before returning it.

Memoization can be used to optimize the performance of many functions that have repeated and expensive computations. By caching the results of function calls, we can avoid unnecessary computations and speed up the execution of the function.

Conclusion

Memoization is a programming concept and can be applied to any programming language. Its absolute goal is to optimize the program. Usually, this problem is seen when programs perform heavy computations. This technique cache all the previous result that is computed so that it will not have to recalculate for the same problem. 

Related Articles: 



Previous Article
Next Article

Similar Reads

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
Tabulation vs Memoization
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 re
10 min read
Linked complete binary tree & its creation
A complete binary tree is a binary tree where each level 'l' except the last has 2^l nodes and the nodes at the last level are all left-aligned. Complete binary trees are mainly used in heap-based data structures. The nodes in the complete binary tree are inserted from left to right in one level at a time. If a level is full, the node is inserted i
15 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Python Set | Pairs of complete strings in two sets
Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together have all characters from ‘a’ to ‘z’. We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each st
2 min read
Minimum time required to complete all tasks with alteration of their order allowed
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "AAABBB", K
8 min read
Find the largest Complete Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is Complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible. Note: All Perfect Binary Trees are Complete Binary tree but reve
15+ min read
Number of refills to complete the journey of N km
Given a number N which represents the total distance in km to be covered by a car on a single road. There are N petrol pumps at a distance of 1 km each(1, 2, 3, ..N). The capacity of the fuel tank of the car is such that at full tank it goes till a distance of K km. The car has to compulsorily stop at M petrol tanks whose distance from the starting
8 min read
Find LCA for K queries in Complete Binary Tree
Given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value x has two children where the left node has the value 2*x and the right node has the value 2*x + 1, you are given K queries of type (ai, bi), and the task is to return the LCA for the node pair ai and
6 min read
Proof that vertex cover is NP complete
Prerequisite - Vertex Cover Problem, NP-Completeness Problem - Given a graph G(V, E) and a positive integer k, the problem is to find whether there is a subset V’ of vertices of size at most k, such that every edge in the graph is connected to some vertex in V’. Explanation - First let us understand the notion of an instance of a problem. An instan
5 min read
Minimum time required to complete a work by N persons together
Given the no. of working hours of N people individually to complete a certain piece of work. The task is to find the number of hours they will take when all work together. Examples: Input: n = 2, a = 6.0, b = 3.0 Output: 2 Hours Input: n = 3, a = 6.0, b = 3.0, c = 4.0 Output: 1.33333 Hours Solution: If a person can do a piece of work in ‘n’ days, t
4 min read
Minimum number of days required to complete the work
Given N works numbered from 1 to N. Given two arrays, D1[] and D2[] of N elements each. Also, each work number W(i) is assigned days, D1[i] and D2[i] (Such that, D2[i] < D1[i]) either of which can be completed. Also, it is mentioned that each work has to be completed according to the non-decreasing date of the array D1[].The task is to find the
6 min read
Maximum Possible Edge Disjoint Spanning Tree From a Complete Graph
Give a complete graph with N-vertices. The task is to find out the maximum number of edge-disjoint spanning tree possible.Edge-disjoint Spanning Tree is a spanning tree where no two trees in the set have an edge in common. Examples: Input : N = 4 Output : 2 Input : N = 5 Output : 2 The maximum number of possible Edge-Disjoint Spanning tree from a c
3 min read
Program to find total number of edges in a Complete Graph
Given N number of vertices of a Graph. The task is to find the total number of edges possible in a complete graph of N vertices.Complete Graph: A Complete Graph is a graph in which every pair of vertices is connected by an edge. Examples: Input : N = 3 Output : Edges = 3 Input : N = 5 Output : Edges = 10 The total number of possible edges in a comp
3 min read
Ways to Remove Edges from a Complete Graph to make Odd Edges
Given a complete graph with N vertices, the task is to count the number of ways to remove edges such that the resulting graph has odd number of edges. Examples: Input: N = 3 Output: 4 The initial graph has 3 edges as it is a complete graph. We can remove edges (1, 2) and (1, 3) or (1, 2) and (2, 3) or (1, 3) and (2, 3) or we do not remove any of th
4 min read
Print path from root to all nodes in a Complete Binary Tree
Given a number N which is the total number of nodes in a complete binary tree where nodes are number from 1 to N sequentially level-wise. The task is to write a program to print paths from root to all of the nodes in the Complete Binary Tree.For N = 3, the tree will be: 1 / \ 2 3 For N = 7, the tree will be: 1 / \ 2 3 / \ / \ 4 5 6 7 Examples: Inpu
9 min read
Number of edges in mirror image of Complete binary tree
Given a complete binary tree of depth H. If the mirror image from the left and the right side of this tree is taken then: Right Mirrored Image: Rightmost node of the every level is connected to mirrored corresponding node. Left Mirrored Image: Left most node of the every level is connected to mirrored corresponding node. The task is to find the num
4 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Find value K in given Complete Binary Tree with values indexed from 1 to N
Given a complete binary tree with values indexed from 1 to N and a key K. The task is to check whether a key exists in the tree or not. Print "true" if the key exists, otherwise print "false". Complete Binary Tree: A Binary Tree is a complete Binary Tree if all the levels are completely filled except possibly the last level and the last level has a
11 min read
Program to find the time remaining for the day to complete
Given the current time in the form of HH::MM, where H represents the hours and M, represents the minutes in a 24-hour time format. The task is to calculate the time remaining for the day to complete as HH::MM.Examples: Input: HH::MM = 00::01 Output: 23::01 Input: HH::MM = 23::55 Output: 00::05 Approach: Since the total minutes in a 24 hour complete
4 min read
Sideways traversal of a Complete Binary Tree
Given a Complete Binary Tree, the task is to print the elements in the following pattern. Let's consider the tree to be: The tree is traversed in the following way: The output for the above tree is: 1 3 7 11 10 9 8 4 5 6 2 Approach: The idea is to use the modified breadth first search function to store all the nodes at every level in an array of ve
15+ min read
Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
Given an array arr[] of size N, the task is to generate a Complete Binary Tree in such a way that sum of the non-leaf nodes is minimum, whereas values of the leaf node corresponds to the array elements in an In-order Traversal of the tree and value of each non-leaf node corresponds to the product of the largest leaf value in the left sub-tree and r
6 min read
Find weight of MST in a complete graph with edge-weights either 0 or 1
Given an undirected weighted complete graph of N vertices. There are exactly M edges having weight 1 and rest all the possible edges have weight 0. The array arr[][] gives the set of edges having weight 1. The task is to calculate the total weight of the minimum spanning tree of this graph. Examples: Input: N = 6, M = 11, arr[][] = {(1 3), (1 4), (
10 min read
Difference between NP hard and NP complete problem
Prerequisite: NP-Completeness NP Problem: The NP problems set of problems whose solutions are hard to find but easy to verify and are solved by Non-Deterministic Machine in polynomial time. NP-Hard Problem: A Problem X is NP-Hard if there is an NP-Complete problem Y, such that Y is reducible to X in polynomial time. NP-Hard problems are as hard as
2 min read
Proof that Hamiltonian Cycle is NP-Complete
Prerequisite: NP-Completeness, Hamiltonian cycle. Hamiltonian Cycle: A cycle in an undirected graph G=(V, E) traverses every vertex exactly once. Problem Statement: Given a graph G=(V, E), the problem is to determine if graph G contains a Hamiltonian cycle consisting of all the vertices belonging to V. Explanation: An instance of the problem is an
4 min read
Proof that Independent Set in Graph theory is NP Complete
Prerequisite: NP-Completeness, Independent set. An Independent Set S of graph G = (V, E) is a set of vertices such that no two vertices in S are adjacent to each other. It consists of non- adjacent vertices. Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph contains an independent set of vertices of size >
5 min read