Lazy array with deferred map and indexOf

0
Sign in

Implement LazyArray, an integer array that supports deferred mapping. Calls to map are recorded but do not run. The recorded functions run only when a query needs a value.

Implement:

  • LazyArray(arr): wraps a list of integers.
  • map(fn) -> LazyArray: returns a new LazyArray that represents applying fn to every element after all functions already recorded. It must not call fn, and it must not change the array it was called on. Calls can be chained, and one array can be mapped more than once into independent chains.
  • indexOf(target) -> int: applies the recorded functions in order and returns the smallest index whose final value equals target, or -1 if there is none.

Constraints:

  • 0 <= len(arr) <= 10^5; a chain may hold thousands of map calls.
  • Mapping functions are pure: same input, same output, no side effects.
  • Do no more work than a query needs. Be ready to explain how you would test that evaluation is really lazy.

Example 1

a = LazyArray([3, 7, 11, 15])
b = a.map(lambda x: x * 3)      # no function runs yet
b.indexOf(21)                   # 1   (values are [9, 21, 33, 45])
b.map(lambda x: x + 1).indexOf(34)  # 2
a.indexOf(11)                   # 2   (a is unchanged)

Example 2

c = LazyArray([5, 8, 5, 8]).map(lambda x: x % 2)
c.indexOf(1)    # 0   (first occurrence)
c.indexOf(2)    # -1
LazyArray([]).map(lambda x: x).indexOf(0)   # -1
DatabricksCodingMediumLast asked Apr 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.