Program to Find Array Type (Even, Odd, or Mixed)
Single-pass algorithm to classify an array as all-even, all-odd, or mixed, with working C, C++, Java, and Python implementations and edge-case analysis.
Classifying an array as all-even, all-odd, or mixed requires exactly one pass and two boolean flags.
The core insight: you don’t need to count even and odd elements separately. You only need to know whether at least one even element exists and whether at least one odd element exists. Two flags, one loop, done.
What “Array Type” Means
Given an integer array, the classification is:
| Condition | Output |
|---|---|
Every element satisfies n % 2 == 0 | Even |
Every element satisfies n % 2 != 0 | Odd |
| At least one even and at least one odd element | Mixed |
Manual trace on {2, 4, 1, 3, 5}:
- Element 2:
2 % 2 == 0, sohasEven = true - Element 4:
4 % 2 == 0, hasEven stays true - Element 1:
1 % 2 != 0, sohasOdd = true - Both flags are now true. Result: Mixed.
No need to continue scanning elements 3 and 5. Once both flags flip, the answer is settled.
Algorithm: Single-Pass Flag Tracking
The approach uses two boolean variables initialised to false:
hasEven: set to true when any element has remainder 0 on division by 2hasOdd: set to true when any element has a non-zero remainder on division by 2
After iterating through the array:
- If
hasEvenis true andhasOddis false: print “Even” - If
hasOddis true andhasEvenis false: print “Odd” - If both are true: print “Mixed”
An optional early exit: if both flags become true mid-loop, break immediately. For short arrays in placement tests this optimisation is cosmetic. For arrays with thousands of elements where the first even and first odd appear early, it skips the rest of the scan entirely.
Why not count even and odd elements separately? You could increment evenCount and oddCount, then compare at the end. It works, but the boolean approach is simpler: you need the presence-or-absence information, not the totals. Flags communicate intent more clearly than counts when totals are irrelevant.
For another single-pass array scan that uses running state instead of nested loops, see find the equilibrium index of an array.
Implementations
All four implementations use the same test input: {2, 4, 1, 3, 5}. Expected output: Mixed.
C
#include <stdio.h>
int main() {
int arr[] = {2, 4, 1, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int hasEven = 0, hasOdd = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
hasEven = 1;
else
hasOdd = 1;
if (hasEven && hasOdd)
break;
}
if (hasEven && hasOdd)
printf("Mixed\n");
else if (hasEven)
printf("Even\n");
else
printf("Odd\n");
return 0;
}
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 1, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
bool hasEven = false, hasOdd = false;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
hasEven = true;
else
hasOdd = true;
if (hasEven && hasOdd)
break;
}
if (hasEven && hasOdd)
cout << "Mixed" << endl;
else if (hasEven)
cout << "Even" << endl;
else
cout << "Odd" << endl;
return 0;
}
Java
public class ArrayType {
public static void main(String[] args) {
int[] arr = {2, 4, 1, 3, 5};
boolean hasEven = false, hasOdd = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
hasEven = true;
else
hasOdd = true;
if (hasEven && hasOdd)
break;
}
if (hasEven && hasOdd)
System.out.println("Mixed");
else if (hasEven)
System.out.println("Even");
else
System.out.println("Odd");
}
}
Python
arr = [2, 4, 1, 3, 5]
has_even = False
has_odd = False
for num in arr:
if num % 2 == 0:
has_even = True
else:
has_odd = True
if has_even and has_odd:
break
if has_even and has_odd:
print("Mixed")
elif has_even:
print("Even")
else:
print("Odd")
Tracing the Python version against a purely even input [2, 4, 6, 8]:
- Element 2:
2 % 2 == 0,has_even = True - Element 4: same,
has_evenstays True - Element 6: same
- Element 8: same
- After loop:
has_even = True,has_odd = False. Output: “Even”.
Correct. The early-exit condition never fires because has_odd never becomes true.
Edge Cases
Empty Array
If n == 0, the loop body never executes. Both flags remain false. Without a guard, the else branch prints “Odd”, which is wrong. Add a check:
if n == 0:
print("Empty")
Most placement problem statements guarantee n >= 1, but defensive code handles it.
Single Element
An array with one element is either even or odd, never mixed. The loop runs once, sets exactly one flag, and the classification is correct without modification.
All Zeros
Zero is even. The expression 0 % 2 evaluates to 0 in C, C++, Java, and Python (per the C arithmetic specification and Python expression rules). An array {0, 0, 0} correctly classifies as “Even”.
Negative Numbers
Parity depends on divisibility by 2, not sign. The value -3 has (-3) % 2 != 0 (the exact result is -1 in C99+/Java or 1 in Python, but both are non-zero). The flag-based approach classifies negatives correctly.
For a related problem involving zero-value handling in integers, see program to replace all 0s with 1 in a given integer.
Complexity Analysis
| Metric | Value |
|---|---|
| Time complexity | O(n) worst case, where n is the array length |
| Best case | O(1) if the first two elements differ in parity |
| Space complexity | O(1) extra space (two boolean variables) |
The approach avoids sorting (which would cost O(n log n) and destroy element order) and avoids counting (which uses the same O(n) time but produces information you don’t need). Two flags are sufficient because the classification is binary on two axes: presence of at least one even element and presence of at least one odd element.
For problems where scan patterns share this single-pass structure, see find all symmetric pairs in an array.
From Array Scans to Pattern Recognition
The flag-tracking pattern here (scan once, track state, classify at the end) is the same structure behind how tokenisers in language models process input sequences. Each token gets examined once; running state accumulates; a final classification emerges. If that parallel interests you, TinkerLLM lets you build and run tokenisation experiments at ₹299, starting from exactly this kind of scan-classify intuition.
Primary sources
Frequently asked questions
Why are zeros classified as even in the array type check?
Zero is divisible by 2 with no remainder. The expression 0 % 2 evaluates to 0 in every language covered here, so zeros always count as even elements when determining array type.
Does the modulus check handle negative numbers correctly?
Yes. In C99+, C++, Java, and Python, n % 2 produces 0 for even negatives and a non-zero value for odd negatives. The parity classification remains correct regardless of sign.
Can the algorithm exit early before scanning all elements?
Yes. Once both hasEven and hasOdd are true, the result is mixed regardless of remaining elements. Adding a break at that point skips unnecessary iterations on large arrays.
What should the program output for an empty array?
Most problem statements guarantee at least one element. If empty input is possible, guard with a size check and output Empty or return a sentinel before entering the loop.
Is this problem asked in placement coding rounds?
It appears as a warm-up array problem in service-tier coding tests. The interviewer checks whether you use a single-pass approach with O(1) space rather than sorting the array or making multiple passes.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)