Repeated and Missing Number

Repeated and Missing Number

 
You are given an array from 1 to n { 1, 3, 5, 3, 2 }. Find the repeated and missing number in the given unsorted array.
 
Input :  int[] array = { 1, 3, 5, 3, 2 };
 
Output: Missing Number : 4 Repeated Number : 3
 
Here is the code
 



package com.diaryreaders.IB;
import java.util.Arrays;
public class RepeatMissingNumber {
public static void main(String[] args) {
int[] array = { 1, 3, 5, 3, 2 };
findRepeatedMissingNum(array);
}
private static void findRepeatedMissingNum(int[] array) {
Arrays.sort(array);
int repeatedNum = -1;
int missingNum = -1; // no repeated and missing num then return -1
int seriesAP = 0;
int seriesSum = array[0];
for (int i = 0; i < array.length - 1; i++) {
if (array[i] == array[i + 1]) {
repeatedNum = array[i];
}
seriesSum += array[i + 1];
}
seriesAP = ((array[array.length - 1] * (array[array.length - 1] + 1)) / 2);
missingNum = seriesAP - seriesSum + repeatedNum;
System.out.println("missingNum : " + missingNum);
System.out.println("repeatedNum : " + repeatedNum);
}
}


Output :

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON