#2630
Memoize II
HardHash MapMemoization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal solution, we will use a HashMap to store results based on the input arguments. This allows for constant time retrieval of cached results, significantly improving performance compared to the brute force approach.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a HashMap to store the results of function calls.
- 2Step 2: For each input, create a unique key based on the input arguments.
- 3Step 3: Check if the key exists in the HashMap.
- 4Step 4: If it exists, return the cached result and increment the call counter.
- 5Step 5: If it does not exist, call the original function, store the result in the HashMap, and increment the call counter.
solution.py13 lines
1def memoize(fn):
2 cache = {}
3 calls = 0
4 def memoized(*args):
5 nonlocal calls
6 key = str(args)
7 if key in cache:
8 return {'val': cache[key], 'calls': calls}
9 result = fn(*args)
10 cache[key] = result
11 calls += 1
12 return {'val': result, 'calls': calls}
13 return memoizedℹ
Complexity note: The time complexity is O(n) because each input is processed in constant time due to the HashMap, resulting in linear performance. The space complexity remains O(n) for storing results.
- 1Memoization can significantly reduce the number of function calls by caching results.
- 2Identical inputs are determined by strict equality (===) in JavaScript.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.