DEV Community

Piyush Acharya
Piyush Acharya

Posted on

JAVASCRIPT SOLUTION BEATS 83% IN MEMORY USAGE

Intuition

The code snippet is a JavaScript implementation of the reduce() method for arrays. The reduce() method is used to apply a function to each element of an array and reduce the array to a single value.

Approach

The reduce() method is called on an array and takes two arguments: a callback function and an initial value. The callback function is executed on each element of the array and takes two arguments: an accumulator and the current element. The accumulator is the value returned by the previous invocation of the callback function, or the initial value if it is the first invocation. The current element is the current element being processed in the array. The callback function returns a value that is used as the accumulator for the next invocation of the callback function. The reduce() method returns the final value of the accumulator after all elements of the array have been processed.

Complexity

  • Time complexity: The time complexity of the reduce() method is O(n), where n is the number of elements in the array. This is because the callback function is executed once for each element in the array.
  • Space complexity: The space complexity of the reduce() method is O(1), because it only uses a constant amount of additional space to store the accumulator and the current element. # Code
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    var res = init
    for (var i = 0; i < nums.length; i++) {
        res = fn(res, nums[i])
    }
    return res;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)