Missing and Repeating in an Array

Last Updated : 9 Feb, 2026

Given an unsorted array arr[] of size n, containing elements from the range 1 to n, it is known that one number in this range is missing, and another number occurs twice in the array, find both the duplicate number and the missing number.

Examples: 

Input: arr[] = [3, 1, 3]
Output: [3, 2]
Explanation: 3 is occurs twice and 2 is missing.

Input: arr[] = [4, 3, 6, 2, 1, 1]
Output: [1, 5]
Explanation: 1 is occurs twice and 5 is missing.

Try It Yourself
redirect icon

[Approach 1] 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.

C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> findTwoElement(vector<int>& arr) {
    
    int n = arr.size();  
    // frequency array to count occurrences
    vector<int> freq(n + 1, 0); 
    int repeating = -1, missing = -1;
    
    // count frequency of each element
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
    
    // identify repeating and missing elements
    for (int i = 1; i <= n; i++) {
        if (freq[i] == 0) missing = i;
        else if (freq[i] == 2) repeating = i;
    }
    
    return {repeating, missing};
}

int main() {
    vector<int> arr = {3, 1, 3};
    vector<int> ans = findTwoElement(arr);
    cout <<