Write a function `sumArray(arr)` that returns the sum of all numbers in the array.
Problem Statement
<p>Write a function <code>sumArray(arr)</code> that returns the sum of all numbers in the array.</p>
Examples
Input: arr = [1, 2, 3, 4, 5]
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Use Array.reduce() to accumulate a sum.
š” Hint 2:
The initial value of the accumulator should be 0.
š” Hint 3:
return arr.reduce((sum, n) => sum + n, 0);
Editorial & Approach
Problem Overview & Intuition
To solve Sum of Array, we consider the execution characteristics of JavaScript engines. Write a function `sumArray(arr)` that returns the sum of all numbers in the array. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use array.reduce() to accumulate a sum).
- Implement Logic: Handle state and transformations efficiently (the initial value of the accumulator should be 0).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function sumArray(arr) {
return arr.reduce((sum, n) => sum + n, 0);
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.