Skip to content

Practice Array Reduce Transformation

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#2626
LeetCode Problem

Array Reduce Transformation

Problem Statement

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.

Source: Array Reduce Transformation on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr; } init = 0
Output
10

# Example 2

Input
nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr * curr; } init = 100
Output
130

# Example 3

Input
nums = [] fn = function sum(accum, curr) { return 0; } init = 25
Output
25

Constraints

0 <= nums.length <= 1000
0 <= nums[i] <= 1000
0 <= init <= 1000

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.