DEV Community

Jen C.
Jen C.

Posted on

LeetCode - Solution for 2626. Array Reduce Transformation

The first attempt by following the pattern shown in the problem description:

type Fn = (accum: number, curr: number) => number

function reduce(nums: number[], fn: Fn, init: number): number {
    if(nums.length === 0) return init;

    let accum = init;
    for(let i = 0; i < nums.length ; i+= 1){
        accum = fn(accum, nums[i]);
    }
    return accum;
};
Enter fullscreen mode Exit fullscreen mode



After reviewing the top-ranked solution, I realized that the early return if(nums.length === 0) return init; is not necessary. The reason is that I have assigned the initial value init to accum with let accum = init;, and it will be returned even if the length of the array nums is 0.

Thus, a better solution should be:

type Fn = (accum: number, curr: number) => number

function reduce(nums: number[], fn: Fn, init: number): number {
    let accum = init;
    for(let i = 0; i < nums.length ; i+= 1){
        accum = fn(accum, nums[i]);
    }
    return accum;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)