2626:- Array Reduce Transformation - LeetCode Solution
IntuitionThe problem requires us to apply a reducer function to an array and return a single accumulated value. This is similar to JavaScript's built-in reduce(
# **Intuition**  
The problem requires us to apply a reducer function to an array and return a single accumulated value. This is similar to JavaScript's built-in `reduce()` method, where we iterate through the array, applying the function at each step while keeping track of an intermediate value.  

# **Approach**  
I explored **three different approaches** to implement this:  

---

# 🔹 **Approach 1: Using `for` Loop**  
```js
var reduce = function (nums, fn, init) {
  let val = init;
  for (let i = 0; i < nums.length; i++) {
    val = fn(val, nums[i]);
  }
  return val;
};
```  
📌 **Explanation:**  
- We initialize `val` with `init`.  
- The `for` loop iterates over each element, updating `val` by applying the function `fn(val, nums[i])`.  
- Finally, we return `val` after all iterations.  
- **This is a straightforward and readable approach.**  

---

# 🔹 **Approach 2: Using `for` Loop with Direct Assignment**  
```js
var reduce = (nums, fn, init) => {
  for (let i = 0; i < nums.length; i++) {
    init = fn(init, nums[i]);
  }
  return init;
};
```  
📌 **Why is this different?**  
- Instead of using an extra variable `val`, we directly update `init`.  
- This makes the code **more concise** while maintaining efficiency.  

---

# 🔹 **Approach 3: Using `forEach()` (Best & Optimized)**  
```js
var reduce = (nums, fn, init) => {
  nums.forEach((val) => {
    init = fn(init, val);
  });
  return init;
};
```  
📌 **Why is this better?**  
- Uses **JavaScript’s built-in `forEach()` method**, which makes it more **readable**.  
- Eliminates the need for manual index handling.  
- **Cleaner and more maintainable code**.  

---

# **Complexity Analysis**  
- **Time Complexity:**  
  - $$O(n)$$ → We iterate through the array once, applying the function to each element.  
- **Space Complexity:**  
  - $$O(1)$$ → We use only a constant amount of extra space for the accumulator.  

---

# **Code**  
```js
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = (nums, fn, init) => {
  nums.forEach((val) => {
    init = fn(init, val);
  });
  return init;
};
```  

---

# **Important Topics to Learn 📚**  
- **Higher-Order Functions**: Functions that take other functions as arguments (like `reduce`).  
- **Iteration Methods**: Understanding `forEach()`, `reduce()`, `map()`, and `filter()` in JavaScript.  
- **Callback Functions**: How functions can be passed as arguments and executed dynamically.  

---

# 🚀 **Support & Feedback**  
✅ If you found this helpful, **please upvote & comment** on my solution!  
💬 Let’s discuss alternative solutions & improvements! 🚀
['JavaScript']