Loading...
Loading...
In React optimization, one of the most powerful techniques is memoization — avoiding redundant computations by caching previously computed results. This mirrors how React.memo, useMemo, and useCallback work internally.
You are tasked with implementing a Memoization Cache that simulates how a React rendering engine would cache expensive component computations. Given a series of function calls (represented as [functionId, arg] pairs), your cache should return the cached result if the same (functionId, arg) pair was seen before, or compute and store a new result otherwise.
The "computation" for any (functionId, arg) pair is defined as: functionId * arg + functionId.
Your goal is to process a list of queries and return the results, while also tracking the total number of cache hits (cases where the result was retrieved from cache instead of recomputed).
Input: A list of queries where each query is [functionId, arg] — both integers.
Output: A list of two elements:
Input: queries = [[1, 2], [1, 2], [2, 3]]
Output: [[4, 4, 8], 1]
Explanation:
[1, 2]: Not cached. Compute 1 * 2 + 1 = 3... wait: functionId * arg + functionId = 1*2+1 = 3. Cache stores (1,2) -> 3. Result: 3.[1, 2]: Already cached! Cache hit. Result: 3.[2, 3]: Not cached. Compute 2 * 3 + 2 = 8. Result: 8.[3, 3, 8], Cache Hits: 1Input: queries = [[3, 4], [3, 4], [3, 4], [5, 0]]
Output: [[16, 16, 16, 5], 2]
Explanation:
[3,4]: Miss. Compute 3*4+3 = 15. Store and return 15.[3,4]: Hit. Return 15.[3,4]: Hit. Return 15.[5,0]: Miss. Compute 5*0+5 = 5. Return 5.[15, 15, 15, 5], Hits: 2Input: queries = [[1, 1]]
Single query, no previous cache. Compute . No cache hits.
1 <= queries.length <= 10^5 1 <= functionId <= 10^4 -10^4 <= arg <= 10^4 All integers are within 32-bit signed integer range
[[2], 0]1*1+1 = 2(functionId, arg) pairs as keys mapped to their computed results.useMemo avoids re-running expensive computations when dependencies haven't changed.functionId and arg must be unique.Design your solution to be O(n) time and space.