NeetCode #947LC-2635EasyJavaScript
← Back to All Problems

#947 · #2635 · Apply Transform Over Each Element in Array(转换数组中的每个元素)

📌 Problem Statement & Constraints

Given an integer array arr and a function fn, return a new array res where res[i] = fn(arr[i], i). The built-in Array.map must not be used.

💡 Core Algorithmic Approaches

  1. Write a plain for loop that stores fn(arr[i], i) into a new array.
  2. Preallocate with new Array(arr.length) to avoid the repeated resizing that push triggers.
  3. A for...of loop also works, but then the index must be maintained manually.
  4. The exercise targets the semantics of map: the callback receives both the element and its index, and a new equal-length array is returned.

💻 Benchmark Python3 Implementation

var map = function(arr, fn) {
    const res = new Array(arr.length);        // preallocate to avoid resizing
    for (let i = 0; i < arr.length; i++) {
        res[i] = fn(arr[i], i);               // second argument is the index
    }
    return res;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over the array.
💾 Space Complexity
O(n): the result array.

⚠️ Interview Pitfalls & Follow-ups

  • Passing only the element: the callback's second argument is the index and must be supplied.
  • Mutating arr in place: map must return a new array and leave the input untouched.
  • Initialising with an empty array and pushing: correct, but preallocation avoids the growth overhead.