Memoize | #2634 | LeetCode Solution

Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode

Problem: Memoize | #2634 | LeetCode

Given a function `fn`, return a memoized version of that function.

A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.

You can assume there are 3 possible input functions: `sum`, `fib`, and `factorial`.

  • `sum` accepts two integers `a` and `b` and returns `a + b`.

  • `fib` accepts a single integer `n` and returns `1` if `n <= 1` or `fib(n - 1) + fib(n - 2)` otherwise.

  • factorial accepts a single integer `n` and returns `1` if `n <= 1` or `factorial(n - 1) * n` otherwise.


Example 1:

Input

"sum"

["call","call","getCallCount","call","getCallCount"]

[[2,2],[2,2],[],[1,2],[]]

Output

[4,4,1,3,2]


Explanation

const sum = (a, b) => a + b;

const memoizedSum = memoize(sum);

memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.

memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.

// Total call count: 1

memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.

// Total call count: 2


Example 2:

Input

"factorial"

["call","call","call","getCallCount","call","getCallCount"]

[[2],[3],[2],[],[3],[]]

Output

[2,6,2,2,6,2]


Explanation

const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));

const memoFactorial = memoize(factorial);

memoFactorial(2); // Returns 2.

memoFactorial(3); // Returns 6.

memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before.

// Total call count: 2

memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before.

// Total call count: 2

Example 3:

Input

"fib"

["call","getCallCount"]

[[5],[]]

Output

[8,1]


Explanation

fib(5) = 8

// Total call count: 1


Solution:

              /**

     * @param {Function} fn

     */

    function memoize(fn) {

        // Create a Map to store cached results

        const cache = new Map(); 


        return function (...args) {

            // Create a unique key based on the input arguments

            const key = args.join(",")


            if (cache.has(key)) {

                // If the result is already cached, return it

                return cache.get(key);

            } else {

                // If not cached, compute the result using the original function

                const result = fn(...args);


                // Cache the result for future use

                cache.set(key, result);


                return result;

            }

        };

    }


Explanation:

To implement the `memoize` function as described, you can use a caching mechanism to store the results of previous function calls based on their input arguments. Here's the code with step-by-step explanations:


Let's break down the code step by step:


1. The `memoize` function is defined, taking a single parameter `fn`, which is the function to be memoized.


2. Inside the `memoize` function, a `cache` variable is created as a new `Map` object. This map will be used to store the results of function calls based on their input arguments.


3. The `memoize` function returns a new function created using a closure. This new function accepts any number of arguments using the rest operator `...args`.


4. Inside the returned function:

   - It creates a unique key based on the input arguments by converting the arguments array into a JSON string using `JSON.stringify(args)`. This key uniquely represents the specific combination of input arguments.


5. It checks if the `cache` already contains a result associated with the computed key using `cache.has(key)`.

   - If the result is already cached, it returns the cached result using `cache.get(key)`.

   - If not cached, it computes the result by invoking the original function `fn` with the provided arguments using `fn(...args)`.


6. After computing the result, it caches the result in the `cache` map using `cache.set(key, result)` so that it can be reused if the same input arguments are encountered again in the future.


7. Finally, it returns the computed result, whether it was fetched from the cache or freshly computed.


In summary, the `memoize` function creates a memoized version of a given function `fn`. It stores the results of previous function calls in a cache based on their input arguments, ensuring that the same inputs do not trigger redundant function calls, and returning the cached result instead.





Related Blogs
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 31st-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

View More