Array Reduce Transformation - Problem

๐ŸŽฏ The Challenge: Build Your Own Array Reduce

Imagine you're a data scientist who needs to aggregate information from a dataset step by step. You have an array of numbers, a reducer function that defines how to combine two values, and an initial value to start with.

Your task is to implement the reduce operation - a fundamental functional programming concept that processes each array element sequentially, accumulating results along the way.

๐Ÿ“ What you need to do:

  • Start with the init value as your accumulator
  • For each element in nums, call fn(accumulator, currentElement)
  • Update the accumulator with the result
  • Return the final accumulated value

Special case: If the array is empty, simply return the initial value.

Note: You cannot use the built-in Array.reduce() method - implement it from scratch!

Input & Output

example_1.py โ€” Sum Array Elements
$ Input: nums = [1, 2, 3, 4], fn = sum, init = 0
โ€บ Output: 10
๐Ÿ’ก Note: Starting with 0: 0+1=1, 1+2=3, 3+3=6, 6+4=10. The final accumulated sum is 10.
example_2.py โ€” Product of Array Elements
$ Input: nums = [1, 2, 3, 4], fn = multiply, init = 1
โ€บ Output: 24
๐Ÿ’ก Note: Starting with 1: 1ร—1=1, 1ร—2=2, 2ร—3=6, 6ร—4=24. The final accumulated product is 24.
example_3.py โ€” Empty Array
$ Input: nums = [], fn = sum, init = 42
โ€บ Output: 42
๐Ÿ’ก Note: Since the array is empty, no operations are performed and we return the initial value 42.

Constraints

  • 0 โ‰ค nums.length โ‰ค 1000
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • Cannot use built-in Array.reduce() method
  • Function fn is a valid reducer function
  • init can be any integer value

Visualization

Tap to expand
InitialValue0Station 1fn(0, 1)= 1Station 2fn(1, 2)= 3Station 3fn(3, 3)= 6Station 4fn(6, 4)= 10FinalProduct10๐Ÿญ Array Reduce Assembly Linenums = [1, 2, 3, 4], fn = sum, init = 01234
Understanding the Visualization
1
Raw Material
Start with initial value as the base product
2
Station 1
First worker adds component 1 using reducer function
3
Station 2
Second worker enhances the product with component 2
4
Final Product
Continue until all components are added
Key Takeaway
๐ŸŽฏ Key Insight: The reduce operation transforms an array into a single value by maintaining state (accumulator) that evolves through each step, making it perfect for aggregation tasks like sum, product, max, or even complex data transformations.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.4K Views
High Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen