Missing and Repeating in an Array
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.
Table of Content
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++ 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 program to find Missing
// and Repeating in an Array
import java.util.*;
class GfG {
static ArrayList<Integer> findTwoElement(int[] arr) {
int n = arr.length;
// Creating frequency array 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
int[] freq = new int[n + 1];
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;
}
}
ArrayList<Integer> result = new ArrayList<>();
result.add(repeating);
result.add(missing);
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 3};
ArrayList<Integer> ans = findTwoElement(arr);
System.out.println(ans.get(0) + " " + ans.get(1));
}
}
# Python program to find Missing
# and Repeating in an Array
def findTwoElement(arr):
n = len(arr)
# Creating frequency list 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
freq = [0] * (n + 1)
repeating = -1
missing = -1
# Find the frequency of all elements.
for i in range(n):
freq[arr[i]] += 1
for i in range(1, n + 1):
# For missing element, frequency
# will be 0.
if freq[i] == 0:
missing = i
# For repeating element, frequency
# will be 2.
elif freq[i] == 2:
repeating = i
return [repeating, missing]
if __name__ == "__main__":
arr = [3, 1, 3]
ans = findTwoElement(arr)
print(ans[0], ans[1])
// C# program to find Missing
// and Repeating in an Array
using System;
using System.Collections.Generic;
class GfG {
static List<int> findTwoElement(int[] arr) {
int n = arr.Length;
// Creating frequency array 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
int[] freq = new int[n + 1];
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 new List<int> { repeating, missing };
}
static void Main() {
int[] arr = {3, 1, 3};
List<int> ans = findTwoElement(arr);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
// JavaScript program to find Missing
// and Repeating in an Array
function findTwoElement(arr) {
let n = arr.length;
// Creating frequency array 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
let freq = new Array(n + 1).fill(0);
let repeating = -1;
let missing = -1;
// Find the frequency of all elements.
for (let i = 0; i < n; i++) {
freq[arr[i]]++;
}
for (let 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];
}
let arr = [3, 1, 3];
let ans = findTwoElement(arr);
console.log(ans[0], ans[1]);
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++ 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 program to find Missing
// and Repeating in an Array
import java.util.*;
class GfG {
static ArrayList<Integer> findTwoElement(int[] arr) {
int n = arr.length;
int repeating = -1;
for (int i = 0; i < n; i++) {
int val = Math.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;
}
}
ArrayList<Integer> result = new ArrayList<>();
result.add(repeating);
result.add(missing);
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 3};
ArrayList<Integer> ans = findTwoElement(arr);
System.out.println(ans.get(0) + " " + ans.get(1));
}
}
# Python program to find Missing
# and Repeating in an Array
def findTwoElement(arr):
n = len(arr)
repeating = -1
for i in range(n):
val = abs(arr[i])
if arr[val - 1] > 0:
arr[val - 1] = -arr[val - 1]
else:
# Element is repeating.
repeating = val
missing = -1
# Value at missing value index
# will be positive.
for i in range(n):
if arr[i] > 0:
missing = i + 1
break
return [repeating, missing]
if __name__ == "__main__":
arr = [3, 1, 3]
ans = findTwoElement(arr)
print(ans[0], ans[1])
// C# program to find Missing
// and Repeating in an Array
using System;
using System.Collections.Generic;
class GfG {
static List<int> findTwoElement(int[] arr) {
int n = arr.Length;
int repeating = -1;
for (int i = 0; i < n; i++) {
int val = Math.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 new List<int> { repeating, missing };
}
static void Main() {
int[] arr = {3, 1, 3};
List<int> ans = findTwoElement(arr);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
// JavaScript program to find Missing
// and Repeating in an Array
function findTwoElement(arr) {
let n = arr.length;
let repeating = -1;
for (let i = 0; i < n; i++) {
let val = Math.abs(arr[i]);
if (arr[val - 1] > 0) {
arr[val - 1] = -arr[val - 1];
}
else {
// Element is repeating.
repeating = val;
}
}
let missing = -1;
// Value at missing value index
// will be positive.
for (let i = 0; i < n; i++) {
if (arr[i] > 0) {
missing = i + 1;
break;
}
}
return [repeating, missing];
}
let arr = [3, 1, 3];
let ans = findTwoElement(arr);
console.log(ans[0], ans[1]);
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++ 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 program to find Missing
// and Repeating in an Array
import java.util.*;
class GfG {
static ArrayList<Integer> findTwoElement(int[] arr) {
int n = arr.length;
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.length; i++) {
s -= arr[i];
ssq -= arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(repeating);
res.add(missing);
return res;
}
public static void main(String[] args) {
int[] arr = {3, 1, 3};
ArrayList<Integer> ans = findTwoElement(arr);
System.out.println(ans.get(0) + " " + ans.get(1));
}
}
# Python program to find Missing
# and Repeating in an Array
def findTwoElement(arr):
n = len(arr)
s = (n * (n + 1)) // 2
ssq = (n * (n + 1) * (2 * n + 1)) // 6
missing = 0
repeating = 0
for num in arr:
s -= num
ssq -= num * num
missing = (s + ssq // s) // 2
repeating = missing - s
return [repeating, missing]
if __name__ == "__main__":
arr = [3, 1, 3]
ans = findTwoElement(arr)
print(ans[0], ans[1])
// C# program to find Missing
// and Repeating in an Array
using System;
using System.Collections.Generic;
class GfG {
static List<int> findTwoElement(int[] arr) {
int n = arr.Length;
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.Length; i++) {
s -= arr[i];
ssq -= arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
return new List<int> { repeating, missing };
}
static void Main() {
int[] arr = { 3, 1, 3 };
List<int> ans = findTwoElement(arr);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
// JavaScript program to find Missing
// and Repeating in an Array
function findTwoElement(arr) {
let n = arr.length;
let s = (n * (n + 1)) / 2;
let ssq = (n * (n + 1) * (2 * n + 1)) / 6;
let missing = 0, repeating = 0;
for (let i = 0; i < arr.length; i++) {
s -= arr[i];
ssq -= arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
return [repeating, missing];
}
let arr = [3, 1, 3];
let ans = findTwoElement(arr);
console.log(ans[0], ans[1]);
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++ 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 program to find Missing
// and Repeating in an Array
import java.util.*;
class GfG {
static ArrayList<Integer> findTwoElement(int[] arr) {
int n = arr.length;
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) != 0) {
x ^= arr[i];
}
else {
y ^= arr[i];
}
// Decide whether (i+1) is in first set
// or second
if (((i + 1) & setBitIndex) != 0) {
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;
}
ArrayList<Integer> result = new ArrayList<>();
result.add(repeating);
result.add(missing);
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 3};
ArrayList<Integer> ans = findTwoElement(arr);
System.out.println(ans.get(0) + " " + ans.get(1));
}
}
# Python program to find Missing
# and Repeating in an Array
def findTwoElement(arr):
n = len(arr)
xorVal = 0
# Get the xor of all array elements
# And numbers from 1 to n
for i in range(n):
xorVal ^= arr[i]
xorVal ^= (i + 1) # 1 to n numbers
# Get the rightmost set bit in xorVal
setBitIndex = xorVal & ~(xorVal - 1)
x, y = 0, 0
# Now divide elements into two sets
# by comparing rightmost set bit
for i in range(n):
# 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
xCnt = sum(1 for num in arr if num == x)
if xCnt == 0:
missing, repeating = x, y
else:
missing, repeating = y, x
return [repeating, missing]
if __name__ == "__main__":
arr = [3, 1, 3]
ans = findTwoElement(arr)
print(ans[0], ans[1])
// C# program to find Missing
// and Repeating in an Array
using System;
using System.Collections.Generic;
class GfG {
static List<int> findTwoElement(int[] arr) {
int n = arr.Length;
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) != 0) {
x ^= arr[i];
}
else {
y ^= arr[i];
}
// Decide whether (i+1) is in first set
// or second
if (((i + 1) & setBitIndex) != 0) {
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 new List<int> { repeating, missing };
}
static void Main() {
int[] arr = {3, 1, 3};
List<int> ans = findTwoElement(arr);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
// JavaScript program to find Missing
// and Repeating in an Array
function findTwoElement(arr) {
let n = arr.length;
let xorVal = 0;
// Get the xor of all array elements
// And numbers from 1 to n
for (let i = 0; i < n; i++) {
xorVal ^= arr[i];
xorVal ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xorVal
let setBitIndex = xorVal & ~(xorVal - 1);
let x = 0, y = 0;
// Now divide elements into two sets
// by comparing rightmost set bit
for (let 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);
}
}
let xCnt = arr.filter(num => num === x).length;
let missing = xCnt === 0 ? x : y;
let repeating = xCnt === 0 ? y : x;
return [repeating, missing];
}
let arr = [3, 1, 3];
let ans = findTwoElement(arr);
console.log(ans[0], ans[1]);
Output
3 2