#2623

Memoize

Medium
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a cache to store results of function calls based on their arguments, ensuring that each unique set of arguments only triggers the function once. This significantly reduces redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a cache object to store results.
  2. 2Step 2: Create a counter to track the number of function calls.
  3. 3Step 3: Define the memoized function that checks the cache before calling the original function.
  4. 4Step 4: Return the cached result if it exists; otherwise, compute, cache, and return the result.
solution.py12 lines
1def memoize(fn):
2    cache = {}
3    call_count = 0
4    def memoized_fn(*args):
5        nonlocal call_count
6        key = str(args)
7        if key not in cache:
8            cache[key] = fn(*args)
9            call_count += 1
10        return cache[key]
11    memoized_fn.getCallCount = lambda: call_count
12    return memoized_fn

Complexity note: The time complexity is linear because each unique input is processed once, and results are cached, preventing redundant calculations.

  • 1Caching results can drastically improve performance.
  • 2Unique inputs require separate cache entries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.