2626. Array Reduce Transformation LeetCode Solution
In this guide, you will get 2626. Array Reduce Transformation LeetCode Solution with the best time and space complexity. The solution to Array Reduce Transformation problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Array Reduce Transformation solution in C++
- Array Reduce Transformation solution in Java
- Array Reduce Transformation solution in Python
- Additional Resources

Problem Statement of Array Reduce Transformation
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.
Example 1:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10
Explanation:
initially, the value is init=0.
(0) + nums[0] = 1
(1) + nums[1] = 3
(3) + nums[2] = 6
(6) + nums[3] = 10
The final answer is 10.
Example 2:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130
Explanation:
initially, the value is init=100.
(100) + nums[0] * nums[0] = 101
(101) + nums[1] * nums[1] = 105
(105) + nums[2] * nums[2] = 114
(114) + nums[3] * nums[3] = 130
The final answer is 130.
Example 3:
Input:
nums = []
fn = function sum(accum, curr) { return 0; }
init = 25
Output: 25
Explanation: For empty arrays, the answer is always init.
Constraints:
0 <= nums.length <= 1000
0 <= nums[i] <= 1000
0 <= init <= 1000
Complexity Analysis
- Time Complexity: Google AdSense
- Space Complexity: Google Analytics
2626. Array Reduce Transformation LeetCode Solution in C++
type Fn = (accum: number, curr: number) => number;
function reduce(nums: number[], fn: Fn, init: number): number {
let ans = init;
for (const num of nums) {
ans = fn(ans, num);
}
return ans;
}
/* code provided by PROGIEZ */
2626. Array Reduce Transformation LeetCode Solution in Java
N/A
// code provided by PROGIEZ
2626. Array Reduce Transformation LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.