← 返回 databricks 的题目列表Implement a Lazy Array (Deferred Evaluation)
类型:online_judge
Implement a Lazy Array (deferred-evaluation array) that computes elements only when they are accessed.
Requirements:
Design a data structure representing an array of length n, where elements are not computed at initialization time but only upon access.
Provide APIs (names may vary, semantics must match):
get(i): return the value at index i (0-indexed). The first access triggers computation.
(Optional) set(i, value_or_fn): set a concrete value or a function that can produce the value.
(Optional) initialize from a generator function f(i) such that element i is computed by calling f(i).
Explain/implement:
How laziness is guaranteed (unaccessed indices are never computed).
Whether repeated get calls recompute or cache results.
Describe how you would test laziness (e.g., counters/logging/mocks to prove unaccessed elements are never evaluated).
Suggested scale: n up to 1e5.
Provide at least 5 test cases covering:
Unaccessed elements must not be computed
Repeated access to the same index
Boundary indices
Large-scale access
Mixed set/get (if supported)
Example
Input
n=5, gen(i)=i*i; do not call get
Output
gen is never invoked (evaluation count = 0)