- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the missing number in a given Array from number 1 to n in Java?
If a single number is missing in an integer array that contains a sequence of numbers values, you can find it basing of the sum of numbers or, basing on the xor of the numbers.
Based on the sum of the numbers −
- The sum of n sequential numbers will be [n*(n+1)]/2. Using this get the sum of the numbers the n numbers.
- Add all the elements in the array.
- Subtract the sum of the numbers in the array from the sum of the n numbers.
Example
import java.util.Scanner; public class MissingNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the n value: "); int n = sc.nextInt(); int inpuArray[] = new int[n]; System.out.println("Enter (n-1) numbers: "); for(int i=0; i<=n-2; i++) { inpuArray[i] = sc.nextInt(); } //Finding the missing number int sumOfAll = (n*(n+1))/2; int sumOfArray = 0; for(int i=0; i<=n-2; i++) { sumOfArray = sumOfArray+inpuArray[i]; } int missingNumber = sumOfAll-sumOfArray; System.out.println("Missing number is: "+missingNumber); } }
Output
Enter the n value: 5 Enter (n-1) numbers: 1 2 4 5 Missing number is: 3
Using XOR operation − Another way to find the missing number is using XOR.
- Find the XOR of all the numbers up ton.
- Find the XOR of all the numbers in the array.
- Then find the XOR of both results.
Example
import java.util.Scanner; public class MissingNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the n value: "); int n = sc.nextInt(); int inpuArray[] = new int[n]; System.out.println("Enter (n-1) numbers: "); for(int i=0; i<=n-2; i++) { inpuArray[i] = sc.nextInt(); } //Finding the missing number int xorArray = inpuArray[0]; //XOR of elements of the array for(int i=1; i<=n-1; i++) { xorArray = xorArray ^ i; } int xorAll = inpuArray[0]; //XOR of elements of the array for(int i=1; i<=n+1; i++) { xorAll = xorAll ^ i; } int missingNumber = xorArray ^ xorAll; System.out.println("Missing number is: "+missingNumber); } }
Output
Enter the n value: 5 Enter (n-1) numbers: 1 2 4 5 Missing number is: 3
Advertisements