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
.
Please solve it without using the built-in Array.reduce
method.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
0 <= nums.length <= 1000
0 <= nums[i] <= 1000
0 <= init <= 1000
Solution
Method 1 – Custom Reduce Implementation
Intuition
Simulate the reduce operation by iteratively applying the reducer function to the accumulator and each element, starting from the initial value.
Approach
Define a function that takes nums
, fn
, and init
. Start with ans = init
, then for each element, update ans = fn(ans, num)
. Return ans
at the end. If nums
is empty, return init
immediately.
Code
|
|
Complexity
- ⏰ Time complexity:
O(N)
- 🧺 Space complexity:
O(1)