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 INPUT nums array: 1 2 3 4 [0] [1] [2] [3] Reducer function: fn = (a, b) => a + b Initial value: init = 0 nums = [1, 2, 3, 4] fn = sum, init = 0 ALGORITHM STEPS 1 Initialize accumulator val = init = 0 2 Process nums[0] val = fn(0, 1) = 1 3 Process nums[1] val = fn(1, 2) = 3 4 Process nums[2] val = fn(3, 3) = 6 5 Process nums[3] val = fn(6, 4) = 10 Functional Composition Flow: 0 --> 1 --> 3 --> 6 --> 10 FINAL RESULT Sum of all elements: 10 Calculation Breakdown: 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6 6 + 4 = 10 Output: 10 OK Key Insight: Functional Composition chains function calls by passing each result as input to the next iteration. The accumulator (val) carries the running result through the entire array, building up the final value. TutorialsPoint - Array Reduce Transformation | Functional Composition
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