Open In App

Missing and Repeating in an Array

Last Updated : 21 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an unsorted array of size n. Array elements are in the range of 1 to n. One number from set {1, 2, …n} is missing and one number occurs twice in the array. The task is to find these two numbers.

Examples: 

Input: arr[] = {3, 1, 3}
Output: 3, 2
Explanation: In the array, 2 is missing and 3 occurs twice.

Input: arr[] = {4, 3, 6, 2, 1, 1}
Output: 1, 5
Explanation: 5 is missing and 1 is repeating.

Using Visited Array – O(n) time and O(n) space

The idea is to use a frequency array to keep track of how many times each number appears in the original array. Since we know the numbers should range from 1 to n with each appearing exactly once, any number appearing twice is our repeating number, and any number with zero frequency is our missing number.

Step by step approach:

  • Create a frequency array of size n+1 initialized with zeros (we use n+1 since numbers range from 1 to n).
  • Traverse the input array and increment the frequency count for each element at its corresponding index in frequency array.
  • Traverse the frequency array from index 1 to n:
    • If any index has frequency 0, that index is our missing number
    • If any index has frequency 2, that index is our repeating number
  • Return both the repeating and missing numbers
C++
// C++ program to find Missing 
// and Repeating in an Array
#include <bits/stdc++.h>
using namespace std;

vector<int> findTwoElement(vector<int>& arr) {
    int n = arr.size();
  
    // Creating frequency vector of size n+1 with
    // initial values as 0. Note that array
    // values will go upto n, that is why we 
    // have taken the size as n+1
    vector<int> freq(n + 1, false); 
    int repeating = -1;
    int missing = -1;
  
    // Find the frequency of all elements.
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
    
    for (int i = 1; i <= n; i++) {
        
        // For missing element, frequency
        // will be 0.
        if (freq[i] == 0) {
            missing = i;
        }
        
        // For repeating element, frequency
        // will be 2.
        else if (freq[i] == 2) {
            repeating = i;
        }
    }
    
    return {repeating, missing};
}

int main() {
    vector<int> arr = {3, 1, 3};
    vector<int> ans = findTwoElement(arr);
    
    cout << ans[0] << " " << ans[1] << endl;
    return 0;
}
Java Python C# Javascript

Output
3 2

Using Array Marking – O(n) time and O(1) space

The idea is to use array elements as indices and mark the visited elements by making them negative.

  • When we encounter an element whose corresponding index is already marked negative, we’ve found our repeating number.
  • After this, any index that still has a positive value indicates that index+1 is our missing number since it was never marked.

Step by step approach:

  • Traverse the array and for each element get its absolute value.
  • Use this value-1 as an index and make the element at that index negative.
    • If we find that the element at that index is already negative, we’ve found our repeating number.
  • After the first traversal, iterate through the array again looking for any positive value
    • When we find a positive value at index i, i+1 is our missing number.
  • Return both the repeating and missing numbers
C++
// C++ program to find Missing 
// and Repeating in an Array
#include <bits/stdc++.h>
using namespace std;

vector<int> findTwoElement(vector<int>& arr) {
    int n = arr.size();
    
    int repeating = -1;

    for (int i = 0; i < n; i++) {
        int val = abs(arr[i]);
        
        if (arr[val - 1] > 0) {
            arr[val - 1] = -arr[val - 1];
        }
        else {
            
            // ELement is repeating.
            repeating = val;
        }
    }
    
    int missing = -1;
    
    // Value at missing value index
    // will be positive.
    for (int i=0; i<n; i++) {
        if (arr[i] > 0) {
            missing = i+1;
            break;
        }
    }
    
    return {repeating, missing};
}

int main() {
    vector<int> arr = {3, 1, 3};
    vector<int> ans = findTwoElement(arr);
    
    cout << ans[0] << " " << ans[1] << endl;
    return 0;
}
Java Python C# Javascript

Output
3 2

Making Two Math Equations – O(n) time and O(1) space

The idea is to use mathematical equations based on the sum and sum of squares of numbers from 1 to n. The difference between expected and actual sums will give us one equation, and the difference between expected and actual sum of squares will give us another equation. Solving these equations yields our missing and repeating numbers.

Step by step approach:

  • Calculate S1 = sum of numbers from 1 to n using formula n*(n+1)/2
  • Calculate S2 = sum of squares of numbers from 1 to n using formula n*(n+1)*(2n+1)/6
  • Find actual sum and sum of squares by traversing the array
  • Let x be missing number and y be repeating number
  • First equation: x – y = (expected sum – actual sum)
  • Second equation: x² – y² = (expected sum of squares – actual sum of squares)
  • Use these equations to solve for x and y
  • Return the repeating and missing numbers
C++
// C++ program to find Missing 
// and Repeating in an Array
#include <bits/stdc++.h>
using namespace std;

vector<int> findTwoElement(vector<int>& arr) {
    int n = arr.size();
  
    int s = (n * (n + 1)) / 2;
    int ssq = (n * (n + 1) * (2 * n + 1)) / 6;
  
    int missing = 0, repeating = 0;
    
    for (int i = 0; i < arr.size(); i++) {
       s -= arr[i];
       ssq -= arr[i] * arr[i];
    }
    
    missing = (s + ssq / s) / 2;
    repeating = missing - s;
    
    return {repeating, missing};
}

int main() {
    vector<int> arr = {3, 1, 3};
    vector<int> ans = findTwoElement(arr);
    
    cout << ans[0] << " " << ans[1] << endl;
    return 0;
}
Java Python C# Javascript

Output
3 2

An Alternate way to make two equations:

  • Let x be the missing and y be the repeating element.
  • Get the sum of all numbers using formula S = n(n+1)/2 – x + y
  • Get product of all numbers using formula P = 1*2*3*…*n * y / x
  • The above two steps give us two equations, we can solve the equations and get the values of x and y.

Note: This method can cause arithmetic overflow as we calculate the sum of squares (or product) and sum of all array elements.

Using XOR – O(n) time and O(1) space

The idea is to use XOR operations to isolate the missing and repeating numbers. By XORing all array elements with numbers 1 to n, we get the XOR of our missing and repeating numbers. Then, using a set bit in this XOR result, we can divide all numbers into two groups, which helps us separate the missing and repeating numbers.

Refer to Find the two numbers with odd occurrences in an unsorted array to understand how groups will be created.

Step by step approach:

  • XOR all array elements and numbers from 1 to n to get XOR of missing and repeating numbers.
  • Find the rightmost set bit in this XOR result using xorVal & ~(xorVal-1).
  • Use this set bit to divide array elements and numbers 1 to n into two groups.
  • XOR elements of first group to get x and second group to get y.
  • Count occurrences of x in original array to determine which is missing and which is repeating.
  • If x appears in array, x is repeating and y is missing; otherwise vice versa.
  • Return both the repeating and missing numbers.
C++
// C++ program to find Missing 
// and Repeating in an Array
#include <bits/stdc++.h>
using namespace std;

vector<int> findTwoElement(vector<int>& arr) {
    int n = arr.size();
    int xorVal = 0;  

    // Get the xor of all array elements
    // And numbers from 1 to n
    for (int i = 0; i < n; i++) {
        xorVal ^= arr[i];
        xorVal ^= (i + 1);  // 1 to n numbers
    }

    // Get the rightmost set bit in xorVal
    int setBitIndex = xorVal & ~(xorVal - 1);
    
    int x = 0, y = 0;

    // Now divide elements into two sets 
    // by comparing rightmost set bit
    for (int i = 0; i < n; i++) {
      
        // Decide whether arr[i] is in first set 
        // or second
        if (arr[i] & setBitIndex) { 
            x ^= arr[i]; 
        }  
        else { 
            y ^= arr[i]; 
        } 
      
        // Decide whether (i+1) is in first set 
        // or second
        if ((i+1) & setBitIndex) { 
            x ^= (i + 1); 
        }
        else { 
            y ^= (i + 1); 
        }
    }

    // x and y are the repeating and missing values.
    // to know which one is what, traverse the array 
    int missing, repeating;
    
    int xCnt = 0;
    for (int i=0; i<n; i++) {
        if (arr[i] == x) {
            xCnt++;
        }
    }
    
    if (xCnt == 0) {
        missing = x;
        repeating = y;
    }
    else {
        missing = y;
        repeating = x;
    }
    
    return {repeating, missing};
}

int main() {
    vector<int> arr = {3, 1, 3};
    vector<int> ans = findTwoElement(arr);
    
    cout << ans[0] << " " << ans[1] << endl;
    return 0;
}
Java Python C# Javascript

Output
3 2




Next Article

Similar Reads

three90RightbarBannerImg