Showing posts with label missing and repeated number in array. Show all posts
Showing posts with label missing and repeated number in array. Show all posts

Saturday, 17 January 2015

How to check Missing and Repeated number in array

 A array size n have element 1-n but one element is missing and one element is repeated .
public class MissingAndRepeatedElement {
static void searchMissingAndRepeated(int []arr){
     for (int i = 0; i < arr.length; i++) {
        if (arr[Math.abs(arr[i])-1]>0) {
            arr[Math.abs(arr[i])-1]=-arr[Math.abs(arr[i])-1];
        }
        else {
            System.out.println("reapted="+Math.abs(arr[i-1]));
        }
     }
        for (int j = 0; j < arr.length; j++) {
            if (arr[j]>0) {
                System.out.println("Missing="+(j+1));
        }       
    }
 }   
public static void main(String[] args) {
    int arr[]={7, 3,4, 5, 5, 6, 2};
    searchMissingAndRepeated(arr);
}       
}