TheAlgorithms/Java · error · IllegalArgumentException
Array should contain an even number of elements
Error message
Array should contain an even number of elements
What it means
Thrown by NonRepeatingElement.findNonRepeatingElements when the input array has an odd length. The algorithm exploits the invariant that the array contains exactly two non-repeating elements with every other element appearing exactly twice — meaning the total length must be even. An odd length violates that contract, so XOR-based partitioning would produce nonsense.
Source
Thrown at src/main/java/com/thealgorithms/maths/NonRepeatingElement.java:35
* 2. The result will be 0.
* In the first case, we will XOR our element with the first number (which is initially 0).
* In the second case, we will XOR our element with the second number (which is initially 0).
* This is how we will get non-repeating elements with the help of bitwise operators.
*/
public final class NonRepeatingElement {
private NonRepeatingElement() {
}
/**
* Finds the two non-repeating elements in the array.
*
* @param arr The input array containing exactly two non-repeating elements and all other elements repeating.
* @return An array containing the two non-repeating elements.
* @throws IllegalArgumentException if the input array length is odd.
*/
public static int[] findNonRepeatingElements(int[] arr) {
if (arr.length % 2 != 0) {
throw new IllegalArgumentException("Array should contain an even number of elements");
}
int xorResult = 0;
// Find XOR of all elements
for (int num : arr) {
xorResult ^= num;
}
// Find the rightmost set bit
int rightmostSetBit = xorResult & (-xorResult);
int num1 = 0;
int num2 = 0;
// Divide the elements into two groups and XOR them
for (int num : arr) {
if ((num & rightmostSetBit) != 0) {
num1 ^= num;View on GitHub (pinned to fdfb9a395b)
Solutions
- Verify the input conforms to the precondition: exactly two elements appear once and all others appear exactly twice.
- If the array legitimately has an odd length, use a different algorithm (e.g., a frequency map) rather than this specialized XOR method.
- Check upstream data assembly for truncation or a dropped element.
Example fix
// before
int[] arr = {2, 3, 5};
int[] res = NonRepeatingElement.findNonRepeatingElements(arr);
// after — use a generic frequency-based approach if input shape is unknown
Map<Integer, Long> freq = Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
List<Integer> res = freq.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList()); Defensive patterns
Strategy: validation
Validate before calling
public static boolean isValidForNonRepeating(int[] arr) {
if (arr.length % 2 != 0) return false;
Map<Integer, Long> freq = new HashMap<>();
for (int v : arr) freq.merge(v, 1L, Long::sum);
long uniqueCount = freq.values().stream().filter(c -> c == 1).count();
return uniqueCount == 2 && freq.values().stream().filter(c -> c > 1).allMatch(c -> c == 2);
}
if (!isValidForNonRepeating(arr)) {
throw new IllegalArgumentException("arr does not match the two-non-repeating precondition");
}
int[] res = NonRepeatingElement.findNonRepeatingElements(arr); Prevention
- Confirm the precondition: exactly two elements appear once, all others exactly twice.
- If input shape is unknown, use a generic frequency-map approach instead of this XOR method.
- Validate array integrity at the data-source boundary.
When it happens
Trigger: Calling findNonRepeatingElements(int[]) on an array whose length % 2 != 0. For example {2, 3, 5} (length 3) or any array where elements do not pair up correctly.
Common situations: Caller misread the method contract and passed an array with a single unique element; data was truncated or an element dropped during transmission; array built from a stream/iterator that ended one element short; off-by-one in a slice operation upstream.
Related errors
- x and y arrays must have the same length.
- Input x-coordinates must be unique.
- baseNumbers must be non-empty.
- n must be non-negative.
- multiplicativePersistence() does not accept negative values
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/c39e32afe2aeb729.
Report an issue: GitHub.