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;
}

Was this page helpful?