Find the Sum of an Array

Solve this Problem
Easy5 min
Topics
Companies
Given an array nums, return the sum of all its elements. Summing is the simplest example of the accumulator patternAccumulator PatternKeeping a running result (a total, count, maximum…) that is updated once per element of a loop.: one variable carries a running result that every element updates. The same shape — initialise, update per element, return — reappears in counting, averaging, finding the maximum and many other array problems.

Test Case 1:

Input:nums = [3, 8, -2, 5]
Output:14
Explanation:3 + 8 − 2 + 5.

Test Case 2:

Input:nums = [7]
Output:7
Explanation:A single value is its own sum.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆-1000000 ≤ nums[i] ≤ 1000000

Try the Dry Run

Approach & Solutions

Running Total in a LoopGood

Start a total at 0 and add each element to it as you walk through the array. After the last element, total holds the sum. This "accumulator" pattern is the template for most array loops.

TimeO(n)
SpaceO(1)
class Solution { public int sumOfArray(int[] nums) { int total = 0; for (int value : nums) { total += value; } return total; } }
Built-in SumOptimal

Use the language's ready-made summing tool: Arrays.stream(nums).sum() in Java, sum() in Python, accumulate in C++ and reduce in JavaScript. They run the same loop internally, but the intent reads in one line. C has no such function, so it keeps the loop.

TimeO(n)
SpaceO(1)
class Solution { public int sumOfArray(int[] nums) { return Arrays.stream(nums).sum(); } }

Related Problems