Problem
Return the total of all numbers in the list. An empty list sums to 0.
Implement sum_array(numbers).
Input
numbers: The list of integers.
Output
Return the sum.
Constraints
0 ≤ length ≤ 100,000; the total fits in a 64-bit integer
Examples
Example 1
Input:
numbers = [1, 2, 3, 4]
Expected output:
expected = 10
Input:
std::vector<long long> numbers = {1, 2, 3, 4};
Expected output:
long long expected = 10;
Input:
long[] numbers = new long[] {1, 2, 3, 4};
Expected output:
long expected = 10;
Explanation
1 + 2 + 3 + 4 = 10.
Example 2
Input:
numbers = []
Expected output:
expected = 0
Input:
std::vector<long long> numbers = {};
Expected output:
long long expected = 0;
Input:
long[] numbers = new long[] {};
Expected output:
long expected = 0;
Explanation
Nothing to add: 0.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
Add every element as you traverse the list once.
Hint 2
Keep a running total instead of building anything extra.
Hint 3
An empty list should stay at 0, so the initial total matters.
Expected complexity
O(n) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.