[Solved] repeatingMissing You are given an array of size N. It contains numbers in the range 1-N(Both inclusive) with Java

repeatingMissing: You are given an array of size N. It contains numbers in the range 1-N(Both inclusive). One of these numbers is repeating and one is missing in the array. Write a program to display these 2 numbers. The output should be the missing number followed by the repeating number separated by a space.

Input:

5
4 1 5 3 1

Output:

2 1

Solution

import java.util.*;
class twoNumbers
{
  static void repeatingMissing(int arr[],int n)
  {
    //write your code here
    int sumn = n*(n+1)/2;

    int total = 0;
    for(int i = 0; i < n; i++){
      total += arr[i];
    }

    int sumsqn = n*(n+1)*(2*n+1)/6;
    int totalsq = 0;

    for(int i = 0; i < n; i++){
      totalsq += Math.pow(arr[i], 2);
    }

    int rep = (((sumsqn - totalsq)/(sumn - total)) + total - sumn)/2;
    int miss = rep - total + sumn;
    System.out.println(miss +" "+ rep);
        
  }

  public static void main(String args[])
  {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int arr[] = new int[n];
    for(int i=0;i<n;i++)
      arr[i]=sc.nextInt();
    repeatingMissing(arr,n);
  }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *