Advertisement
Home Data Structure Arrays Sum of Negative Elements in an Array

Sum of Negative Elements in an Array

0
Advertisement

Title: Sum of Negative Elements in an Array

In this guide, you will learn how to compute the sum of all negative elements in an integer array using Java. The problem looks small on paper, yet it quietly exercises everything a beginner needs to get right: looping over an array, writing a clean guard condition, choosing a correct accumulator, and reasoning about edge cases such as an empty array or a null reference.

By the end of this article, you will have a complete Java program, a line-by-line explanation, a dry run on a fresh input, three worked examples, a checklist of mistakes to avoid, and a set of interview follow-up questions that mirror what a real interviewer will ask after you solve the base problem.

Understanding the Problem

You are given an array of integers. The task is to return the sum of only those elements that are strictly less than zero. Positive values and zero contribute nothing to the result. For example, the array {3, -1, -4, 2, -5} contains three negative numbers whose sum is -10, so the function should return -10.

Two subtle definitions make this problem interview-worthy. First, zero is not negative, so 0 must be ignored, not added. Second, if the array has no negative elements at all, the correct answer is 0 (the empty sum), not an error. Keeping these two rules in mind as you read the code will make the implementation feel obvious.

Approach / Algorithm Steps

The algorithm is a single linear scan. You walk the array once, check whether each element is negative, and add it to a running total if it is.

  1. Validate the input: if the array reference is null, throw IllegalArgumentException so the caller sees the error instead of a confusing NullPointerException.
  2. Create an accumulator sum and initialize it to 0. This value is also the correct answer when the array has no negatives.
  3. Iterate over every element of the array with an enhanced for loop so the intent (visit each value) is explicit.
  4. For each element, test whether value < 0. The strict less-than operator excludes zero, which is what the problem requires.
  5. If the test passes, add the value to sum using sum += value. Because value is already negative, the running total naturally decreases.
  6. After the loop ends, return sum. If the array was empty or contained no negatives, the loop never executed its if-branch and sum is still 0.

Java Program

The following program is a complete, compilable Java class. Save it as SumOfNegativeElements.java, compile with javac, and run with java SumOfNegativeElements.

Java
public class SumOfNegativeElements {
    public static int sumOfNegatives(int[] numbers) {
        if (numbers == null) {
            throw new IllegalArgumentException("Input array must not be null");
        }
        int sum = 0;
        for (int value : numbers) {
            if (value < 0) {
                sum += value;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] numbers = {4, -2, 7, -8, 0, -1, 5};
        int result = sumOfNegatives(numbers);
        System.out.println("Sum of negative elements: " + result);
    }
}

Explanation of the Program

The class SumOfNegativeElements exposes a single static helper sumOfNegatives and a main method that demonstrates how to call it. Keeping the logic in a reusable static method, rather than inside main, is the pattern you want to use in interviews because it is immediately unit-testable.

Inside sumOfNegatives, the first guard rejects a null array by throwing IllegalArgumentException. This matters because the next line would otherwise crash with a NullPointerException that carries no helpful message. Explicit validation turns a mystery into a clear contract violation.

The accumulator sum starts at 0, which is both the mathematical identity for addition and the correct answer when the array holds no negatives. The enhanced for loop visits each element exactly once, and the condition value < 0 isolates the elements we care about. Using < rather than <= is deliberate: it keeps zero out of the sum, in line with the problem statement.

The compound assignment sum += value adds a negative number to sum, which drives the running total downward. Once the loop finishes, sum already holds the final answer, and the method simply returns it. The main method shows a canonical driver: build an input, call the helper, and print the result.

Step-by-Step Trace

To see the algorithm in motion, trace it on the fresh input {5, -3, 2, -7, -1, 6}. The expected result is -11, the sum of the three negative elements.

Iterationvaluevalue < 0?sum (before)sum (after)
15no00
2-3yes0-3
32no-3-3
4-7yes-3-10
5-1yes-10-11
66no-11-11

At the end of iteration i, sum holds the sum of all negative values in numbers[0..i-1]. That is the loop invariant, and it is why the final value of sum is exactly the answer when the loop terminates.

Examples

Example 1: All elements are negative

When every element is negative, the sum equals the sum of the entire array. There is no selection step that filters anything out.

Java
int[] numbers = {-4, -2, -9, -1};
int result = sumOfNegatives(numbers);
System.out.println(result);
// Output: -16

Example 2: No negative elements

If the array contains only positive numbers, the condition value < 0 is never true, so sum remains at its initial value of 0.

Java
int[] numbers = {10, 20, 30};
int result = sumOfNegatives(numbers);
System.out.println(result);
// Output: 0

Example 3: Mix of negatives, positives, and zero

Zeros and positives are skipped by the value < 0 check, so only -5 and -10 contribute to the final sum.

Java
int[] numbers = {0, -5, 5, -10, 10};
int result = sumOfNegatives(numbers);
System.out.println(result);
// Output: -15

Common Mistakes to Avoid

A handful of specific errors trip up most beginners on this problem. Watch for these before you submit your code.

  • Using <= instead of < – counts zero as negative, so an input like {0, 0, 0} still returns 0 but {0, -3} is handled correctly only by coincidence. Switch the condition to value < 0 so zero is excluded by definition.
  • Taking the absolute value of each element – produces a positive sum like 16 instead of -16 for {-4, -2, -9, -1}. Add value directly, not Math.abs(value); the sign of the answer is part of the contract.
  • Initializing sum to a non-zero value – using Integer.MIN_VALUE or an arbitrary negative seed poisons the result for an empty or all-positive array. Always initialize sum = 0 so the empty sum is correct by construction.
  • Ignoring overflow for very large arrays – adding many Integer.MIN_VALUE-sized values can silently wrap around a 32-bit int. If the input domain allows it, accumulate into a long and either return a long or validate the final value fits in an int.
  • Returning early from the loop – a return sum inside the if branch, or an unnecessary break, stops the scan after the first negative and gives a partial answer. Only return after the loop has finished so every element is considered.

Edge Cases to Test

Walk through this list before declaring the solution finished. The first few are the ones an interviewer will almost certainly ask about.

  • Empty array
  • Null array reference
  • Single-element array with a negative value
  • Single-element array with a positive value or zero
  • All-negative array
  • All-positive array
  • Array containing zeros among the negatives
  • Integer.MIN_VALUE present (overflow risk when accumulated)

Additional Considerations

The time complexity is O(n), where n is the length of the array, because each element is examined exactly once. There is no way to do better in the worst case: without visiting an element, you cannot know whether it is negative. The space complexity is O(1), since only the sum accumulator is allocated regardless of input size.

The overflow point is worth a second thought. An int in Java holds values down to Integer.MIN_VALUE, which is -2,147,483,648. Summing two such values already underflows a 32-bit int. For adversarial inputs or very large arrays, prefer a long accumulator and either return long or throw if the result does not fit in an int. For most interview inputs, a plain int is enough.

Interview Follow-up Questions

Interviewers almost never stop at the base problem. These are the follow-ups you should be ready for, each with a hint toward the right approach.

  • What if you also need the count of negative numbers alongside the sum? – return a small record or int pair; the loop body increments one more counter without changing the overall complexity.
  • What if the array is sorted in ascending order? – all negatives sit at the front, so a binary search for the first non-negative index lets you sum the prefix with a single loop over just the negative segment.
  • What if the input arrives as a stream of unknown length? – keep a running accumulator and update it on each element; termination comes from end-of-stream rather than an array index.
  • What if the array holds billions of elements and does not fit in memory? – partition the input, compute the negative sum of each partition independently, then add the partition sums. The partition step is embarrassingly parallel and maps cleanly onto parallelStream or MapReduce.
  • How would you make this work for a read-only input with strict memory constraints? – the current solution already uses O(1) extra memory and does not mutate the input, so it already satisfies the constraint; be ready to prove this out loud.

Conclusion

Summing the negative elements of an array is a one-pass, constant-space algorithm, but it is also an excellent interview warm-up. It forces you to be careful about the definition of negative, to handle an empty or null input gracefully, and to reason about overflow when the input is adversarial. Nail those details and the rest is a short loop.

Try adapting the code to return the product of negatives, the smallest negative, or the index of the first negative; each variation reuses the same scan skeleton with a different reducing operation. You can learn more about array problems in Java: Arrays.