Repeat and Missing Number Array - The Coding Shala

Home >> Interview Questions >> Repeat and missing Number Array

Repeat and Missing Number Array Solution

Problem Statement::
You are given a read-only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note that in your output A should precede B.

Repeat and Missing Number Array Java - The Coding Shala
Example:
Input:[3 1 2 5 3] 

Output:[3, 4] 

A = 3, B = 4
Solution 1: (Java)

public class Solution {
    public ArrayList<Integer> repeatedNumber(final List<Integer> A) {
        int n = A.size();
        ArrayList<Integer> C=new ArrayList<Integer>();
        int[] arr=new int[n+1];
       for(int i=0;i<n+1;i++) arr[i]=0;
             
        for(int i=0;i<A.size();i++) arr[A.get(i)]++;
       
        int A1=0,B=0;
        for(int i=1;i<n+1;i++){
            if(arr[i]>1) A1 = i;
            if(arr[i]==0) B=i;
        }
        C.add(A1);
        C.add(B);
        return C;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala