Array Reduce Transformation - Problem
๐ฏ The Challenge: Build Your Own Array Reduce
Imagine you're a data scientist who needs to aggregate information from a dataset step by step. You have an array of numbers, a reducer function that defines how to combine two values, and an initial value to start with.
Your task is to implement the reduce operation - a fundamental functional programming concept that processes each array element sequentially, accumulating results along the way.
๐ What you need to do:
- Start with the
initvalue as your accumulator - For each element in
nums, callfn(accumulator, currentElement) - Update the accumulator with the result
- Return the final accumulated value
Special case: If the array is empty, simply return the initial value.
Note: You cannot use the built-in Array.reduce() method - implement it from scratch!
Input & Output
example_1.py โ Sum Array Elements
$
Input:
nums = [1, 2, 3, 4], fn = sum, init = 0
โบ
Output:
10
๐ก Note:
Starting with 0: 0+1=1, 1+2=3, 3+3=6, 6+4=10. The final accumulated sum is 10.
example_2.py โ Product of Array Elements
$
Input:
nums = [1, 2, 3, 4], fn = multiply, init = 1
โบ
Output:
24
๐ก Note:
Starting with 1: 1ร1=1, 1ร2=2, 2ร3=6, 6ร4=24. The final accumulated product is 24.
example_3.py โ Empty Array
$
Input:
nums = [], fn = sum, init = 42
โบ
Output:
42
๐ก Note:
Since the array is empty, no operations are performed and we return the initial value 42.
Constraints
- 0 โค nums.length โค 1000
- -1000 โค nums[i] โค 1000
- Cannot use built-in Array.reduce() method
- Function fn is a valid reducer function
- init can be any integer value
Visualization
Tap to expand
Understanding the Visualization
1
Raw Material
Start with initial value as the base product
2
Station 1
First worker adds component 1 using reducer function
3
Station 2
Second worker enhances the product with component 2
4
Final Product
Continue until all components are added
Key Takeaway
๐ฏ Key Insight: The reduce operation transforms an array into a single value by maintaining state (accumulator) that evolves through each step, making it perfect for aggregation tasks like sum, product, max, or even complex data transformations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code