




Sponsored
Sponsored
This approach simply involves directly iterating through the elements of the array using a loop, starting with the initial value. For each element, apply the reducer function and update the accumulated result. This approach mimics the behavior of the JavaScript Array.reduce method.
Time Complexity: O(n), where n is the number of elements in the array because we loop through each element once.
Space Complexity: O(1), as we use only a fixed amount of additional space.
In this Java solution, we define a static method reduce that accepts an array, a function, and an initial value. We use Java's functional interface IntBinaryOperator for our function. The reduction is performed through a for-each loop over the array. The sum method adds two integers.
This approach employs a recursive strategy to apply the reducer function on each element of the array. By defining a base case for the recursion (i.e., an empty array returns the initial value), the recursion continues until all elements are processed. Care must be taken with recursion due to stack size limitations for large inputs.
Time Complexity: O(n), for traversing each element.
Space Complexity: O(n), due to recursion stack consumption.
1function reduceRecursive(nums, fn, init, index = 0) {
2    if (index >= nums.length) return init;
3    return fn(reduceRecursive(nums, fn, init, index + 1), nums[index]);
4}
5
6function sum(accum, curr) {
7    return accum + curr;
8}
9
10const nums = [1, 2, 3, 4];
11const init = 0;
12const result = reduceRecursive(nums, sum, init);
13console.log(result);In JavaScript, the recursive function reduceRecursive invokes itself with an incremented index until the array is exhausted. Applying the reduction function step by step, it forms the result recursively.