This is the Java Program to Find the Missing Element in an Integer Array.
Given an array of n-1 integers having no duplicates, and containing the integers in the range 1 to n.
Find out the missing integer.
Example:
Array = [ 1, 2, 4, 5]
Output :
Missing integer = 3
Take two variables to say x and y, in x store the XOR of all array elements and in y store the XOR of integers from 1 to n. Finally, take the result of XOR of x and y, this result is our missing integer.
Here is the source code of the Java Program to Find the Missing Element in an Integer Array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Missing Element in an Integer Array.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MissingInteger {
// Function to calculate XOR values and return the missing integer.
static int findMissingInteger(int[] array){
int i;
int XOR1, XOR2;
XOR1 = array[0];
XOR2 = 1;
for(i=1;i<array.length;i++){
XOR1 ^= array[i];
XOR2 ^= (i+1);
}
XOR2 ^=(i+1);
return (XOR2 ^ XOR1);
}
// Function to read the input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the range of the values (starts from 1)");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size-1];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
}
int missing = findMissingInteger(array);
System.out.println("The missing integer is " + missing);
}
}
1. The function findMissingInteger(), initializes the variables XOR1 to array[0] and XOR2 to 1.
2. The loop for(i=1; i<array.length; i++) is used to iterate through the array and store the XOR of its elements in XOR1 and XOR of first n-1 integers in XOR2.
3. The statement XOR2^=(i+1) XOR’s the integer n.
4. The statement (XOR1^XOR2) returns the missing integers.
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the range of the values (starts from 1) 5 Enter array elements 1 2 4 5 The missing integer is 3 Case 2 (Simple Test Case - another example): Enter the range of the values (starts from 1) 8 Enter array elements 8 7 6 5 4 3 2 The missing integer is 1
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Java Internship
- Practice BCA MCQs
- Check Java Books
- Apply for Computer Science Internship
- Practice Programming MCQs