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
Apply Transform Over Each ElementInput:arr = [1, 2, 3]fn = (x, i) => x + i + 1123index 0index 1index 2Apply transformation function2461+0+12+1+13+2+1Output:[2, 4, 6]
Understanding the Visualization
1
Input
Array [1,2,3] and function fn(x,i) = x + i + 1
2
Process
Apply function to each element with its index
3
Output
Transformed array [2,4,6]
Key Takeaway
🎯 Key Insight: Transform each element using both its value and index position
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