Advertisement
Home Data Structure Arrays Check if an Array Contains Only Positive or Negative Numbers

Check if an Array Contains Only Positive or Negative Numbers

0
Advertisement

Title: Check if an Array Contains Only Positive or Negative Numbers

In this guide, you will learn how to check whether a Java array contains only positive numbers, only negative numbers, or a mix of both. This classification shows up often in interviews because it tests whether you can track two conditions in a single pass instead of scanning the array more than once.

We will build a checkArraySign method that walks the array once, flags whether a positive or negative value has appeared, and exits early the moment the signs conflict. Along the way you will see a full trace, the common mistakes beginners make around zero, and a set of interview follow-up questions.

Understanding the Problem

Given an array of integers, you need to decide which of three categories it falls into: every element is strictly greater than zero, every element is strictly less than zero, or the elements mix positive and negative values. A zero in the array rules out both the only positive and only negative categories, since zero is neither.

The naive approach loops through the array twice, once to check for positives and once for negatives. The better approach tracks both conditions during a single pass and stops as soon as the answer is known.

Approach / Algorithm Steps

  1. Validate the input: if numbers is null or empty, throw an IllegalArgumentException, since the question is undefined for zero elements.
  2. Declare two boolean flags, hasPositive and hasNegative, both starting as false.
  3. Loop through the array once, inspecting each element in turn.
  4. If the current element is greater than zero, set hasPositive to true.
  5. If the current element is less than zero, set hasNegative to true.
  6. If the current element equals zero, return "MIXED" immediately, since zero is neither positive nor negative.
  7. Right after updating the flags, check whether both are now true; if so, return "MIXED" without scanning the rest of the array.
  8. If the loop finishes without a mixed result, return "ALL_POSITIVE" when hasPositive is true, otherwise return "ALL_NEGATIVE".

Java Program

Here is the complete implementation. The checkArraySign method returns a String result and the main method exercises it against three sample arrays.

Java
public class ArraySignChecker {
    public static String checkArraySign(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            throw new IllegalArgumentException("Array must contain at least one element");
        }

        boolean hasPositive = false;
        boolean hasNegative = false;

        for (int number : numbers) {
            if (number > 0) {
                hasPositive = true;
            } else if (number < 0) {
                hasNegative = true;
            } else {
                return "MIXED";
            }

            if (hasPositive && hasNegative) {
                return "MIXED";
            }
        }

        return hasPositive ? "ALL_POSITIVE" : "ALL_NEGATIVE";
    }

    public static void main(String[] args) {
        int[] allPositive = {4, 8, 15, 16, 23, 42};
        int[] allNegative = {-3, -7, -1, -9};
        int[] mixedSigns = {5, -2, 9, -8};

        System.out.println(checkArraySign(allPositive));
        System.out.println(checkArraySign(allNegative));
        System.out.println(checkArraySign(mixedSigns));
    }
}

Explanation of the Program

The method walks the array exactly once and relies on two boolean flags instead of two separate loops. This keeps the algorithm at O(n) time with O(1) extra space.

  • hasPositive and hasNegative start as false and only ever flip to true; neither is ever reset inside the loop.
  • A zero element returns "MIXED" immediately, because only positive and only negative are defined strictly and exclude zero from both.
  • The check if (hasPositive && hasNegative) runs right after updating the flags, so the method exits the moment a conflict is detected instead of scanning the remaining elements.
  • If the loop completes without returning, exactly one of the two flags is true, so the final ternary chooses between "ALL_POSITIVE" and "ALL_NEGATIVE".

Step-by-Step Trace

Consider the input [3, 5, -2, 4, -6, 8]. The method should detect the sign conflict at index 2 and return "MIXED" without ever inspecting indices 3 through 5.

Iterationnumbers[i]hasPositive (before)hasNegative (before)hasPositive (after)hasNegative (after)
13falsefalsetruefalse
25truefalsetruefalse
3-2truefalsetruetrue

At the end of each iteration, hasPositive and hasNegative together record every sign seen so far. The moment both become true, the method returns "MIXED" on the spot, which is why indices 3 through 5 are never examined.

Examples

Example 1: Array With Only Positive Numbers

Every element is greater than zero, so hasNegative never flips and the loop runs to completion.

Java
int[] numbers = {10, 20, 30, 40};
System.out.println(checkArraySign(numbers));
// Output: ALL_POSITIVE

Example 2: Array Containing a Zero

The zero at index 1 triggers the dedicated zero branch, so the array is classified as mixed even though no element is negative.

Java
int[] numbers = {5, 0, 3};
System.out.println(checkArraySign(numbers));
// Output: MIXED (zero is neither positive nor negative)

Example 3: Early Exit on Mixed Signs

Only the first two elements determine the result; the early return means the remaining eight elements are never visited.

Java
int[] numbers = {7, -1, 9, 9, 9, 9, 9, 9, 9, 9};
System.out.println(checkArraySign(numbers));
// Output: MIXED (returned right after index 1)

Common Mistakes to Avoid

These are the mistakes candidates actually make when solving this problem, not generic advice.

  • Treating zero as positive – using number >= 0 instead of number > 0 makes an array like {0, 1, 2} wrongly report ALL_POSITIVE. Compare with strict > and <, and handle zero as its own case.
  • Skipping the early exit - looping through the entire array even after a sign conflict is already confirmed wastes time on large inputs. Return "MIXED" as soon as both hasPositive and hasNegative are true.
  • Returning a single boolean - a method like isAllPositive cannot represent ALL_NEGATIVE or MIXED, which pushes callers into confusing double-negative conditions. Return a three-state result such as a String constant or an enum instead.
  • Forgetting the empty-array case - with an empty array the loop never runs, so hasPositive stays false and the final ternary silently returns "ALL_NEGATIVE". Throw an IllegalArgumentException up front for null or empty arrays instead.

Edge Cases to Test

A candidate who lists these cases unprompted signals a systematic approach to the interviewer.

  • Empty array
  • Single-element array
  • All positive elements
  • All negative elements
  • Mixed positive and negative elements
  • Array containing one or more zeros
  • Integer.MIN_VALUE / Integer.MAX_VALUE present
  • Null array reference

Additional Considerations

The algorithm runs in O(n) time in the worst case, when the array truly contains only one sign and the loop must visit every element. Space usage is O(1) beyond the two boolean flags, since no auxiliary array or collection is created.

On arrays where the signs conflict early, the actual running time is much better than O(n) because of the early return, though the worst-case bound remains O(n).

  • String vs enum return type - a String result like "MIXED" is easy to print directly, but an enum such as ArraySign { ALL_POSITIVE, ALL_NEGATIVE, MIXED } gives the compiler a chance to catch typos and unhandled cases in a switch statement.
  • Zero handling is a design decision - this implementation treats any zero as an automatic MIXED result; a variant of the problem might instead ask you to ignore zeros entirely, which would change step 6 of the approach.

Interview Follow-up Questions

These variations probe whether you understand the approach well enough to adapt it, not just recite it.

  • What if you need separate counts of positive, negative, and zero elements instead of a single classification? - replace the two booleans with three counters incremented in the same single pass.
  • What if the numbers arrive as a stream of unknown length rather than a fixed array? - keep hasPositive and hasNegative as running state updated per incoming value; the early-exit check still applies the moment both become true.
  • What if you must answer this query repeatedly on different sub-ranges of the same array? - precompute prefix counts of positive and negative elements so any range query reduces to an O(1) lookup instead of a fresh scan.
  • What if the array holds floating-point numbers and values extremely close to zero should count as zero? - replace the exact == 0 comparison with a small epsilon threshold around zero before classifying a value as positive or negative.

Conclusion

Checking whether an array is entirely positive, entirely negative, or mixed comes down to tracking two conditions in one pass and knowing when to stop early. The same pattern of flag-tracking with an early exit shows up in many other single-pass array problems, so it is worth internalizing beyond this specific question.

Try adapting checkArraySign to return an enum, to ignore zeros, or to work over a List instead of a primitive array. You can learn more about array-based problems like this one on our Arrays category page.