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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)