Apply Transform Over Each Element in Array - Problem

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

The returned array should be created such that returnedArray[i] = fn(arr[i], i), where the function receives both the element value and its index as parameters.

Important: You must implement this without using the built-in Array.map() method.

Example: If arr = [1, 2, 3] and fn = (x, i) => x + i, then the result should be [1+0, 2+1, 3+2] = [1, 3, 5].

Input & Output

example_1.js โ€” Basic Addition
$ Input: arr = [1, 2, 3], fn = (x, i) => x + i
โ€บ Output: [1, 3, 5]
๐Ÿ’ก Note: For each element, we add its value to its index: arr[0]=1+0=1, arr[1]=2+1=3, arr[2]=3+2=5
example_2.js โ€” Multiplication
$ Input: arr = [10, 20, 30], fn = (x, i) => x * 2
โ€บ Output: [20, 40, 60]
๐Ÿ’ก Note: Each element is doubled (index is ignored in this function): 10*2=20, 20*2=40, 30*2=60
example_3.js โ€” Edge Case
$ Input: arr = [5], fn = (x, i) => x * i
โ€บ Output: [0]
๐Ÿ’ก Note: Single element at index 0: 5 * 0 = 0. This demonstrates how index can significantly affect the result

Constraints

  • 0 โ‰ค arr.length โ‰ค 1000
  • -109 โ‰ค arr[i] โ‰ค 109
  • fn returns an integer
  • The transformation function fn is always provided and valid

Visualization

Tap to expand
Assembly Line Array TransformationInput Conveyor1pos:02pos:13pos:2Transformationfn(value, pos)= value + posWorkerOutput Conveyor135Step-by-Step ProcessStep 1Input: 1, pos=01 + 0 = 1Output: 1Step 2Input: 2, pos=12 + 1 = 3Output: 3๐ŸŽฏ Each element is processed exactly once with its position information
Understanding the Visualization
1
Input Conveyor
Products arrive on the input belt, each with a position number
2
Transformation Station
Worker applies fn(product, position) to transform each item
3
Output Collection
Transformed products are placed on the output belt in order
4
Final Result
Complete transformed array is ready for delivery
Key Takeaway
๐ŸŽฏ Key Insight: Array transformation is a linear operation that requires exactly one pass through the input data, making it inherently O(n) in both time and space complexity.
Asked in
Google 45 Microsoft 38 Amazon 42 Meta 35
52.0K Views
High Frequency
~12 min Avg. Time
2.2K 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