Category: Easy | Concepts used: Array iteration, accumulator pattern, integer overflow mitigation, Java Streams
Problem Statement
Given an integer array, find the sum of all its elements.
Input : [1, 2, 3, 4, 5] Output: 15
Input : [10] Output: 10 (single element)
Examples (with edge scenarios)
| # | Input Array | Sum | Why |
|---|---|---|---|
| 1 | [1, 2, 3, 4, 5] | 15 | Typical array |
| 2 | [10] | 10 | Single element sum is the element itself |
| 3 | [] | 0 | Empty array has a sum of 0 |
| 4 | [-5, 5, -3, 3] | 0 | Opposing signs cancel out |
| 5 | [2000000000, 2000000000] | 4000000000 | Exceeds Integer.MAX_VALUE โ requires long accumulator |
โ ๏ธ Common Beginner Mistake
Mistake Impact Fix Accumulating large values in intInteger overflow (wraps to a negative number silently) Use longfor the accumulator variableDeclaring accumulator inside the loop Scope limits variable, resets every iteration Declare accumulator outside the loop block
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm whether the array may be null or empty, whether duplicates and original order matter, whether the method may modify the input, and whether the answer should contain values or original indices. These choices can change both the code and the best data structure.
Analogy: Grocery Checkout Register
Imagine you are checking out at a supermarket with a conveyor belt filled with grocery items:
- The cash register screen starts at zero (
sum = 0). - The cashier scans the first item. The price is added to the screen (
sum = 1). - The cashier scans the second item. The price is added to the screen (
sum = 1 + 2 = 3). - This continues until all items on the belt are scanned.
- The final number displayed is the total price (sum) of all your groceries! If the conveyor belt is empty, the register naturally displays
0.
Solution 1 โ Simple Loop (Recommended Starting Point)
This is the standard iterative approach using an index accumulator.
Intuition
By maintaining a running sum variable and adding each array index item to it sequentially, we count all values in a single pass.
public class SumArray {
public static long sumArray(int[] arr) {
if (arr == null) {
return 0;
}
long sum = 0; // Using long to prevent integer overflow
for (int i = 0; i < arr.length; i++) {
sum += arr[i]; // Add each element
}
return sum;
}
public static void main(String[] args) {
System.out.println(sumArray(new int[]{1, 2, 3, 4, 5})); // 15
System.out.println(sumArray(new int[]{})); // 0
System.out.println(sumArray(new int[]{-5, 5, -3, 3})); // 0
}
}
Output:
15
0
0
Dry Run (arr = [1, 2, 3, 4, 5])
sum = 0
i = 0: sum = 0 + 1 = 1
i = 1: sum = 1 + 2 = 3
i = 2: sum = 3 + 3 = 6
i = 3: sum = 6 + 4 = 10
i = 4: sum = 10 + 5 = 15
Final sum = 15
Solution 2 โ Using Enhanced for-loop (Slightly Cleaner Syntax)
This solution loops through values directly without index variables.
Intuition
By using Javaโs foreach syntax, we avoid handling array index boundaries and prevent off-by-one errors.
public class SumArrayForEach {
public static long sumArray(int[] arr) {
if (arr == null) {
return 0;
}
long sum = 0;
for (int num : arr) { // Walks values directly
sum += num;
}
return sum;
}
public static void main(String[] args) {
System.out.println(sumArray(new int[]{1, 2, 3, 4, 5})); // 15
}
}
Solution 3 โ Using Java Streams
This approach uses Stream API reductions for a declarative implementation.
Intuition
By creating a primitive stream of integers from the array, we can use built-in reduction operations like .sum() to compute the total.
import java.util.Arrays;
public class SumArrayStream {
public static long sumArray(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
// Map to a long stream first to prevent internal overflow during addition
return Arrays.stream(arr).asLongStream().sum();
}
public static void main(String[] args) {
System.out.println(sumArray(new int[]{1, 2, 3, 4, 5})); // 15
}
}
๐ Visual Flowchart
graph TD
Start["Input Array arr"] --> Empty{"arr is null/empty?"}
Empty -->|Yes| RetZero["Return 0"]
Empty -->|No| Init["Initialize sum = 0 (long)"]
Init --> Loop{"i < arr.length?"}
Loop -->|Yes| Add["sum += arr[i]"]
Add --> IncLoop["i++"]
IncLoop --> Loop
Loop -->|No| End["Return sum"]
Interviewer Insights
This is a classic question evaluating core programming fundamentals.
Follow-up questions you might get:
- โWhat happens if the array elements sum to more than Integer.MAX_VALUE?โ โ If you use
int sum, it wraps around and outputs a corrupted negative number. Proactively upgrading the accumulator to along(64-bit) tells the interviewer you write secure, production-grade code. - โHow does the stream solution handle empty arrays?โ โ
Arrays.stream().sum()natively returns0for empty streams, which matches the mathematical definition.
Quick Recap
| Approach | Time Complexity | Space Complexity (Auxiliary) | Overflow Protected? | Interview Signal |
|---|---|---|---|---|
| Simple Loop | (O(N)) | (O(1)) | Yes (using long) | Standard loop iteration, robust |
| Enhanced Loop | (O(N)) | (O(1)) | Yes (using long) | Clean structure, safe from off-by-one errors |
| Streams | (O(N)) | (O(1)) | Yes (using asLongStream()) | Functional paradigm, modern Java features |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed