DEV Community

Piyush Acharya
Piyush Acharya

Posted on

Fastest JS Solution - Beats 75% of Solutions with 50 MS Runtime

Intuition

The code snippet is a JavaScript function that takes an array and a function as input and returns a new array with the function applied to each element of the input array.

Approach

The approach used in the code snippet is to loop through each element of the input array and apply the given function to it. The result of the function is then stored in a new array.

Complexity

  • Time complexity: The time complexity of the map function is O(n), where n is the length of the input array. This is because the function loops through each element of the input array once and applies the given function to it.
  • Space complexity: The space complexity of the map function is O(n), where n is the length of the input array. This is because the function creates a new array of the same length as the input array to store the results of the function applied to each element of the input array. # Code
/**
 * @param {number[]} arr
 * @param {Function} fn
 * @return {number[]}
 */
var map = function(arr, fn) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
        newArr[i] = fn(arr[i], i);
    }
    return newArr;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)