00:00

Problem Statement

Input/Output Examples

Visual Explanation

The running total starts at 0 and grows by one element per step. Because the total is a long, each int is widened before it is added, so the result cannot overflow.

Approaches

Both approaches add every element once. The key difference from a naive version is the type of the total.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Each element is added once, and the only extra storage is the running total.

Interview Tips and Recommended Approach

  • Mention overflow before the interviewer does. int total wraps around without an error; 2000000000 + 2000000000 becomes -294967296.
  • Know that IntStream.sum() returns an int. Use asLongStream() or mapToLong() when the total might be large.
  • State the empty-array result. The sum of nothing is 0, and your loop should return it without a special case.
  • Prepare the follow-ups: average, sum of even elements, and prefix sums all build on this loop.

Recommended Approach: Loop With a long Total

Why: it is a single readable loop, it returns 0 for an empty array naturally and the long total removes the overflow problem. It also makes the type choice visible, which interviewers often probe.