Apply Transform Over Each Element in Array - Problem

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.

Input & Output

Example 1 — Add One to Each Element
$ Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
💡 Note: Apply fn to each element: fn(1,0)=2, fn(2,1)=3, fn(3,2)=4
Example 2 — Add Index to Element
$ Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
💡 Note: Add index to each element: fn(1,0)=1+0=1, fn(2,1)=2+1=3, fn(3,2)=3+2=5
Example 3 — Constant Function
$ Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
💡 Note: Function returns constant: fn(10,0)=42, fn(20,1)=42, fn(30,2)=42

Constraints

  • 0 ≤ arr.length ≤ 1000
  • -109 ≤ arr[i] ≤ 109
  • fn returns an integer

Visualization

Tap to expand
Transform Over Each Element in Array INPUT Input Array: arr 1 i=0 2 i=1 3 i=2 Mapping Function: fn function plusone(n) { return n + 1; } Input Values arr = [1, 2, 3] arr.length = 3 ALGORITHM STEPS 1 Pre-allocate Array result = new Array(3) 2 Loop Through Array for (i = 0; i < 3; i++) 3 Apply Transform result[i] = fn(arr[i], i) 4 Return Result return result Iterations i arr[i] fn(arr[i]) result 0 1 2 [2] 1 2 3 [2,3] 2 3 4 [2,3,4] FINAL RESULT Transformed Array 2 i=0 3 i=1 4 i=2 Output [2, 3, 4] Status: OK Each element +1 No Array.map used Pre-allocated array Key Insight: Pre-allocating the result array with new Array(arr.length) is more memory-efficient than pushing elements one by one. This approach avoids repeated array resizing and achieves O(n) time complexity. TutorialsPoint - Apply Transform Over Each Element in Array | Pre-allocated Array Approach
Asked in
Google 25 Facebook 20 Amazon 15
25.8K Views
Medium Frequency
~10 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen