




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.
1import java.util.function.IntBinaryOperator;
2
3public class ArrayReducerRecursive {
4    public static int reduceRecursive(int[] nums, int index, IntBinaryOperator fn, int init) {
5        if (index == nums.length) return init;
6        return fn.applyAsInt(reduceRecursive(nums, index + 1, fn, init), nums[index]);
7    }
8
9    public static int sum(int accum, int curr) {
10        return accum + curr;
11    }
12
13    public static void main(String[] args) {
14        int[] nums = {1, 2, 3, 4};
15        int init = 0;
16        int result = reduceRecursive(nums, 0, ArrayReducerRecursive::sum, init);
17        System.out.println(result);
18    }
19}This Java implementation uses recursion, processing the array from the last index back to the first. Each recursive call handles a smaller segment of the array, accumulating results. Its base case returns the initialized value.