Coding problem · Easy · Basics
Sum of an Array
Easy Algorithms & data structures
Return the sum of the numbers in nums. An empty array sums to 0.
Example 1
Input: nums = [1,2,3,4] Output: 10
Example 2
Input: nums = [] Output: 0
Hints
Hint 1
Start a total at 0 and add each number to it.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
A running total: start at 0, add each element. Built-ins like sum() or reduce do the same.
Reference solution
function sumArray(nums) {
let total = 0;
for (const n of nums) total += n;
return total;
}
function sumArray(nums: number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
def sum_array(nums: list[int]) -> int:
total = 0
for n in nums:
total += n
return total
<?php
function sumArray(array $nums): int
{
return array_sum($nums);
}
class Solution {
public int sumArray(int[] nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy