KatInterview

Building Map and Filter from a Reduce Foundation

Data Structure DesignModel answer
HardModel answerData Structure Designhigher-order-functionsfunctional-programmingdata-structures

Last updated

Implement a reduce operation, then express map and filter purely in terms of that reducer without independent iteration.

You need to explain and implement a reduce operation, then show how map and filter can be built entirely on top of it—without their own separate loops or traversals.

Part 1: Specify and Implement Reduce

Define the behavior of a reduce function. Your explanation should cover:

  • The signature: what arguments does reduce accept?
  • The reducer callback: what parameters does it receive and what does it return?
  • The accumulator: where does the initial value come from?
  • Iteration order: in what sequence are elements processed?
  • Empty collections: what does reduce return when given an empty input?
  • Invariants: what guarantee holds after processing each element?

Provide a concrete implementation in a language of your choice.

Part 2: Derive Map and Filter

Using only your reduce implementation, build:

  1. map: transforms each input element via a function, producing a collection of the same length
  2. filter: keeps only elements satisfying a predicate, potentially shrinking the output

Your implementations must:

  • Use reduce internally—no separate iteration
  • Preserve input order
  • Handle empty inputs correctly
  • Not mutate the original collection

Part 3: Composition Example

Demonstrate how these operations compose by showing a short example that chains map and filter to transform some structured data (you may invent a simple hypothetical dataset like a list of records).

Constraints

  • Pick one language and state its relevant semantics (e.g., whether arrays are immutable, whether callbacks can throw)
  • Your reduce must be eager (not lazy)
  • Explain any performance considerations related to accumulator updates

Clarifying Questions to Consider

  • Should the initial accumulator be required or optional?
  • Can reducer callbacks mutate external state or raise exceptions?
  • Must map and filter return new collections or may they modify in place?

Hints

Hint 1

The reducer callback typically receives (accumulator, current_element) and returns the next accumulator.

Hint 2

For map, the accumulator can be a growing collection; for filter, conditionally add elements based on the predicate.

Hint 3

Composition means passing the output of one operation as input to the next—no intermediate materialization tricks needed.