TechByteByByte

Check if a List Contains Only Odd Numbers - Java

An easy QA/automation coding interview question: check if a List Contains Only Odd Numbers, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Arrays#Lists#Loops#Streams#Easy#Java

Category: Easy | Concepts used: Early exit optimization, conditional loops, short-circuiting streams, vacuous truth


Problem Statement

Given a list (or array) of integers, check whether every element is odd.

Input : [1, 3, 5, 7]        Output: true
Input : [1, 2, 5, 7]        Output: false   (2 is even, breaking the rule)

Examples (with edge scenarios)

#InputOutputWhy
1[1, 3, 5, 7]trueEvery element is odd
2[1, 2, 5, 7]false2 breaks the rule
3[] (empty list)trueVacuous truth โ€” a statement about all elements is trivially true if no elements exist
4[7]trueSingle element is odd
5[-3, -5]trueNegative odd numbers are correctly identified (since -3 % 2 == -1 which is non-zero)

โš ๏ธ Common Beginner Mistake

MistakeImpactFix
Using n % 2 == 1 for odd checksNegative odd numbers (e.g. -3) evaluate to -3 % 2 == -1, marking them wrongly as evenCheck for even first (n % 2 == 0) or check n % 2 != 0 for odd
Returning false for an empty listViolates logical truth rulesEmpty arrays should return true by default (vacuous truth)

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: Checking IDs at a VIP Lounge

Imagine you are a security guard stationed at the door of a VIP lounge. The owner has given you a strict instruction: โ€œOnly allow entry to odd-numbered members. If you spot even a single even-numbered member inside, shut down the lounge immediately.โ€

  • You walk around the lounge checking IDs (looping through elements).
  • The moment you find a member with an even ID (num % 2 == 0), you immediately declare the rule broken and sound the alarm (return false). You donโ€™t need to waste time checking the remaining guests.
  • If you check everyone and find no even IDs, the rule is successfully satisfied (return true).
  • The Empty Lounge (Empty Array): If there are no guests in the lounge, the statement โ€œEvery guest in the lounge has an odd IDโ€ is technically true because there is nobody in the room to break the rule! This is known in logic as a Vacuous Truth.

Solution 1 โ€” Loop Through and Check Each Element (with Early Exit)

This is the standard iterative approach using early exit.

Intuition

To prove a list has only odd numbers, we only need to find a single even number to disprove it. This asymmetry allows us to optimize performance by exiting the loop the moment we see a single even value (short-circuiting).

public class OnlyOddCheck {
    public static boolean containsOnlyOdd(int[] arr) {
        if (arr == null) {
            return false;
        }

for (int num : arr) {
            if (num % 2 == 0) {  // Found an even number (rule breaker)
                return false;    // Short-circuit immediately
            }
        }
        return true; // Reached the end with zero even numbers
    }

public static void main(String[] args) {
        System.out.println(containsOnlyOdd(new int[]{1, 3, 5, 7})); // true
        System.out.println(containsOnlyOdd(new int[]{1, 2, 5, 7})); // false
        System.out.println(containsOnlyOdd(new int[]{}));            // true
        System.out.println(containsOnlyOdd(new int[]{-3, -5}));      // true
    }
}

Output:

true
false
true
true

Dry Run (arr = [1, 2, 5, 7])

num = 1 -> 1 % 2 = 1 (not even) -> continue
num = 2 -> 2 % 2 = 0 (even!) -> return false immediately (skips evaluating 5 and 7)

Solution 2 โ€” Using Java Streams (allMatch)

This is the modern declarative approach using Java streams.

Intuition

The stream method allMatch takes a predicate and checks if all elements satisfy it. Just like our loop, allMatch is short-circuiting; it terminates computation as soon as a non-matching element is evaluated.

import java.util.Arrays;

public class OnlyOddCheckStream {
    public static boolean containsOnlyOdd(int[] arr) {
        if (arr == null) {
            return false;
        }
        // Returns true automatically for empty arrays
        return Arrays.stream(arr).allMatch(num -> num % 2 != 0);
    }

public static void main(String[] args) {
        System.out.println(containsOnlyOdd(new int[]{1, 3, 5, 7})); // true
        System.out.println(containsOnlyOdd(new int[]{1, 2, 5, 7})); // false
    }
}

Output:

true
false

๐Ÿ“Š Visual Flowchart

graph TD
    Start["Input List/Array"] --> NullCheck{"Array is null?"}
    NullCheck -->|Yes| RetFalse["Return False"]
    NullCheck -->|No| Loop{"More elements?"}
    Loop -->|Yes| Fetch["num = next element"]
    Fetch --> Check{"num % 2 == 0?"}
    Check -->|Yes| FoundEven["Return False (Early Exit)"]
    Check -->|No| Loop
    Loop -->|No| End["Return True (Vacuous Truth)"]

Interviewer Insights

This is a great filter question for checking mathematical edge cases and short-circuit optimization awareness.

Follow-up questions you might get:

  • โ€œWhat is a vacuous truth?โ€ โ†’ Explain that in math and programming logic, a universal claim (โ€œall elements are Xโ€) is true by default if there are no elements, because there is no counterexample in the set that can invalidate the claim.
  • โ€œWhy is the early exit check critical?โ€ โ†’ If the first item in an array of a million elements is even, we avoid running 999,999 pointless remainder calculations. This changes the best-case execution time from (O(N)) to (O(1)).

Quick Recap

ApproachShort-circuits?Time Complexity (Worst Case)Space ComplexityInterview Signal
Iterative LoopYes(O(N))(O(1))Demonstrates core logic flow and early-exit optimization
allMatch() StreamYes(O(N))(O(1))Clean, functional, modern Java style
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed