NeetCode #949LC-2626EasyJavaScript
← Back to All Problems#949 · #2626 · Array Reduce Transformation(数组归约运算)
📌 Problem Statement & Constraints
Given an integer array
nums, a reducer fn, and an initial value init, return fn(...fn(fn(init, nums[0]), nums[1]), ...). The built-in Array.reduce must not be used.💡 Core Algorithmic Approaches
- Keep an accumulator
accinitialised toinit. - Walk the array left to right, updating
acc = fn(acc, nums[i])at each step. - Return
accwhen the array is exhausted. - Crucially, an empty array must still return
init.
💻 Benchmark Python3 Implementation
var reduce = function(nums, fn, init) {
let acc = init;
for (let i = 0; i < nums.length; i++) {
acc = fn(acc, nums[i]); // fn(accumulator, current)
}
return acc; // empty array -> init
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass over the array.
💾 Space Complexity
O(1): a single accumulator.
⚠️ Interview Pitfalls & Follow-ups
- Swapping the callback arguments to
fn(nums[i], acc): the reducer signature is(accumulator, current). - Returning 0 or
undefinedfor an empty array: the required result isinit. - Implementing it recursively without a base case: an empty array would recurse forever or return the wrong value.