{"record":{"id":"c39e32afe2aeb729","repo":"TheAlgorithms/Java","slug":"array-should-contain-an-even-number-of-elements","errorCode":null,"errorMessage":"Array should contain an even number of elements","messagePattern":"Array should contain an even number of elements","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/NonRepeatingElement.java","lineNumber":35,"sourceCode":" * 2. The result will be 0.\n * In the first case, we will XOR our element with the first number (which is initially 0).\n * In the second case, we will XOR our element with the second number (which is initially 0).\n * This is how we will get non-repeating elements with the help of bitwise operators.\n */\npublic final class NonRepeatingElement {\n    private NonRepeatingElement() {\n    }\n\n    /**\n     * Finds the two non-repeating elements in the array.\n     *\n     * @param arr The input array containing exactly two non-repeating elements and all other elements repeating.\n     * @return An array containing the two non-repeating elements.\n     * @throws IllegalArgumentException if the input array length is odd.\n     */\n    public static int[] findNonRepeatingElements(int[] arr) {\n        if (arr.length % 2 != 0) {\n            throw new IllegalArgumentException(\"Array should contain an even number of elements\");\n        }\n\n        int xorResult = 0;\n\n        // Find XOR of all elements\n        for (int num : arr) {\n            xorResult ^= num;\n        }\n\n        // Find the rightmost set bit\n        int rightmostSetBit = xorResult & (-xorResult);\n        int num1 = 0;\n        int num2 = 0;\n\n        // Divide the elements into two groups and XOR them\n        for (int num : arr) {\n            if ((num & rightmostSetBit) != 0) {\n                num1 ^= num;","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java#L17-L53","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nint[] arr = {2, 3, 5};\nint[] res = NonRepeatingElement.findNonRepeatingElements(arr);\n\n// after — use a generic frequency-based approach if input shape is unknown\nMap<Integer, Long> freq = Arrays.stream(arr).boxed()\n    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\nList<Integer> res = freq.entrySet().stream()\n    .filter(e -> e.getValue() == 1)\n    .map(Map.Entry::getKey)\n    .collect(Collectors.toList());","handlingStrategy":"validation","validationCode":"public static boolean isValidForNonRepeating(int[] arr) {\n    if (arr.length % 2 != 0) return false;\n    Map<Integer, Long> freq = new HashMap<>();\n    for (int v : arr) freq.merge(v, 1L, Long::sum);\n    long uniqueCount = freq.values().stream().filter(c -> c == 1).count();\n    return uniqueCount == 2 && freq.values().stream().filter(c -> c > 1).allMatch(c -> c == 2);\n}\n\nif (!isValidForNonRepeating(arr)) {\n    throw new IllegalArgumentException(\"arr does not match the two-non-repeating precondition\");\n}\nint[] res = NonRepeatingElement.findNonRepeatingElements(arr);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["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."],"tags":["math","bit-manipulation","invalid-argument","array-length"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}