Array Reduce Transformation - Problem

Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.

This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The ultimate value of val is then returned.

If the length of the array is 0, the function should return init.

Note: Please solve it without using the built-in Array.reduce method.

Input & Output

Example 1 — Sum Reduction
$ Input: nums = [1,2,3,4], fn = sum, init = 0
Output: 10
💡 Note: Step by step: 0+1=1, 1+2=3, 3+3=6, 6+4=10. Final result is 10.
Example 2 — Multiplication
$ Input: nums = [1,2,3,4], fn = mult, init = 1
Output: 24
💡 Note: Step by step: 1*1=1, 1*2=2, 2*3=6, 6*4=24. Final result is 24.
Example 3 — Empty Array
$ Input: nums = [], fn = sum, init = 42
Output: 42
💡 Note: Empty array returns the initial value unchanged: 42.

Constraints

  • 0 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000
  • -1000 ≤ init ≤ 1000

Visualization

Tap to expand
Array Reduce Transformation Overviewinit: 01234InitialArray Elementsfn: sumReducer Function0+1=11+2=33+3=66+4=10Result: 10Final accumulated value after processing all elements
Understanding the Visualization
1
Input
Array [1,2,3,4], function sum, initial value 0
2
Process
Apply fn(accumulator, element) sequentially
3
Output
Final accumulated result: 10
Key Takeaway
🎯 Key Insight: The reducer function transforms each array element while maintaining state through an accumulator
Asked in
Meta 25 Google 30 Amazon 20
22.3K Views
Medium Frequency
~10 min Avg. Time
890 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