← 返回 databricks 的题目列表Lazy Array (Lazy Evaluation) with Unit Tests
类型:online_judge
Question: Implement a Lazy Array (Lazy Evaluation) with Unit Tests
Implement a LazyArray that supports lazy evaluation. It takes a function to generate elements on demand, and must not generate all elements upfront. When an index is accessed for the first time, compute it via the function and cache it.
Requirements
Implement LazyArray:
Constructor: LazyArray(n: int, f: Callable[[int], Any])
n is the array length.
f(i) generates the element at index i.
get(i: int) -> Any
Return the element at index i.
On first access, call f(i) and cache.
Subsequent accesses to the same index must not call f(i) again.
set(i: int, value: Any) -> None
Set index i to value and override the cache (later get(i) must not call f(i)).
Constraints
Define out-of-bounds behavior clearly (exception or error value).
f(i) can be expensive; avoid unnecessary calls.
Thread-safety is not required unless you choose to support it.
Unit Tests
Cover at least:
Laziness: constructor does not call f; only the first get(i) calls it once.
Caching: repeated get(i) does not call f(i) again.
After set(i, value), get(i) returns the new value and does not call f(i).
Out-of-bounds behavior.
Scale
n: 1 <= n <= 1,000,000
Number of operations Q: 1 <= Q <= 200,000
I/O (online-judge style)
Input:
First line: n Q
Second line: integer seed (used by generator)
Next Q lines:
GET i
SET i value
Generator function is defined as:
f(i) = (i * 1315423911 + seed) % 1000000007
Output:
For each GET, print the element value
Example
Input
5 5
7
GET 0
GET 0
SET 0 42
GET 0
GET 1
Output
7
7
42
918877915