




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.
public class ArrayReducer {
    public static int Reduce(int[] nums, Func<int, int, int> fn, int init) {
        int result = init;
        foreach (var num in nums) {
            result = fn(result, num);
        }
        return result;
    }
    public static int Sum(int accum, int curr) {
        return accum + curr;
    }
    public static void Main() {
        int[] nums = {1, 2, 3, 4};
        int init = 0;
        int result = Reduce(nums, Sum, init);
        Console.WriteLine(result);
    }
}This C# program defines the method Reduce which leverages the Func delegate to apply the reduction function over the array. The reduction function Sum simply sums 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.