DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Predicting Ad Viewability With XGBoost Regressor Algorithm
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Metal and the Simulated Annealing Algorithm
  • Balancing Security and UX With Iterative Experimentation

Trending

  • A Complete Guide to Modern AI Developer Tools
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Creating a Web Project: Caching for Performance Optimization
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Memoization: Make Recursive Algorithms Efficient

Memoization: Make Recursive Algorithms Efficient

Learn how to use a technique called memoization to make recursive algorithms efficient through dynamic programming.

By 
Yogen Rai user avatar
Yogen Rai
·
Aug. 08, 18 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
22.6K Views

Join the DZone community and get the full member experience.

Join For Free

Memoization is a technique for implementing dynamic programming to make recursive algorithms efficient. It often has the same benefits as regular dynamic programming without requiring major changes to the original more natural recursive algorithm.

Basic Idea

  • The first thing is to design the natural recursive algorithm.
  • If recursive calls with the same arguments are repeatedly made, then the inefficient recursive algorithm can be memoized by saving these subproblem solutions in a table so they do not have to be recomputed.

Implementation

To implement memoization to recursive algorithms, a table is maintained with subproblem solutions, but the control structure for filling in the table occurs during normal execution of the recursive algorithm. This can be summarized in steps:

  1. A memoized recursive algorithm maintains an entry in a table for the solution to each of subproblem,
  2. Each table entry initially contains a special value to indicate that entry has yet to be filled in.
  3. When the subproblem is first encountered, its solution is computed and stored in the table.
  4. Subsequently, the value is looked up rather than computed

To illustrate the steps above, let's take an example for computing nth Fibonacci number with a recursive algorithm as:

// without memoization
static int fib(int n) {
    if (n == 0 || n == 1) return n;

    return fib(n - 1) + fib(n - 2);
}

The runtime for the above algorithm is roughly O(2n). This can be visualized for fib(5) as below:

 Fibonacci-Series-5

Memoization.

In the above tree, you can see the same values (for example fib(1), fib(0).. ) are being computed repeatedly. In fact, each time we compute fib (i), we could just cache this result and use it later. So, when we call fib (n), we shouldn't have to do much more than 0 (n) calls, since there's only O(n) possible values we can throw at fib(n).

// memoized version
static int fibonacciMemo(int n) {
    // entry table to cache the computed values
    int[] fibs = new int[n + 1];
    // initialize entry table with -1 to say value has to calculated
    Arrays.fill(fibs, -1);

    return fib(n, fibs);
}

static int fib(int n, int[] fibs) {
    if (n == 0 || n == 1) return n;

    if (fibs[n] == -1) {
        fibs[n] = fib(n - 1, fibs) + fib(n - 2, fibs);
    }

    return fibs[n];
}

You can see, how easily with just a small modification, were able to make this function to run in O(n) time as:

memoized-recursive

Advantages

  • The algorithm does not have to be transformed into an iterative one.
  • It often offers the same (or better) efficiency as usual dynamic programming approach.
  • For calculation of the 45th Fibonacci number, it took 5136ms in my machine (i7 Octa-core):
    long startTime = System.currentTimeMillis();
    System.out.println(fib(45));
    System.out.println("Time taken (w/o memo): " + (System.currentTimeMillis() - startTime) + " ms");
    But with memoization, it is 0 ms.

This method is also sometimes called Top-Down Dynamic Programming.

Isn't this a cool thing for making iterative algorithms efficient?

All source code presented above is available on GitHub.

Algorithm Memoization Dynamic programming

Opinions expressed by DZone contributors are their own.

Related

  • Predicting Ad Viewability With XGBoost Regressor Algorithm
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Metal and the Simulated Annealing Algorithm
  • Balancing Security and UX With Iterative Experimentation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!