Missing and Repeating in an Array
Last Updated :
20 Aug, 2024
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. Find these two numbers.
Examples:
Input: arr[] = {3, 1, 3}
Output: Missing = 2, Repeating = 3
Explanation: In the array, 2 is missing and 3 occurs twice
Input: arr[] = {4, 3, 6, 2, 1, 1}
Output: Missing = 5, Repeating = 1
Using Visited Array:
- Create a temp array visited[] of size n+1 with all initial values as false. Note that array values go upto n, that is why we have taken size as n+1.
- Traverse the input array arr[], and do the following for each arr[i]
- if(visited[arr[i]] == false), set visited[arr[i]) = true;
- if(visited[arr[i]] == true) output “arr[i]” //repeating number
- Traverse visited[] and output ‘i’ corresponding to the element of array visited[] having value as false. (This is the missing number)
C++
#include <bits/stdc++.h>
using namespace std;
void printTwoElements(vector<int>& arr) {
int n = arr.size();
// Creating visited vector of size n+1 with
// initial values as false. Note that array
// values will go upto n, that is why we
// have taken the size as n+1
vector<bool> visited(n + 1, false);
int repeating = -1;
int missing = -1;
for (int i = 0; i < n; i++) {
if (visited[arr[i]]) {
repeating = arr[i];
} else {
visited[arr[i]] = true;
}
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
missing = i;
break;
}
}
cout << "Repeating : " << repeating << endl;
cout << "Missing : " << missing << endl;
}
int main() {
vector<int> arr = { 7, 3, 4, 5, 5, 6, 2 };
printTwoElements(arr);
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
void printTwoElements(int arr[], int n) {
// Creating visited vector of size n+1 with
// initial values as false. Note that array
// values will go upto n, that is why we
// have taken the size as n+1
bool visited[n + 1];
int repeating = -1, missing = -1;
for (int i = 0; i <= n; i++) {
visited[i] = false;
}
for (int i = 0; i < n; i++) {
if (visited[arr[i]]) {
repeating = arr[i];
} else {
visited[arr[i]] = true;
}
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
missing = i;
break;
}
}
printf("Repeating : %d\n", repeating);
printf("Missing : %d\n", missing);
}
int main() {
int arr[] = { 7, 3, 4, 5, 5, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printTwoElements(arr, n);
return 0;
}
Java
import java.util.Arrays;
public class Main {
static void printTwoElements(int[] arr)
{
int n = arr.length;
// Creating visited vector of size n+1 with
// initial values as false. Note that array
// values will go upto n, that is why we
// have taken the size as n+1
boolean[] visited = new boolean[n + 1];
int repeating = -1, missing = -1;
Arrays.fill(visited, false);
for (int i = 0; i < n; i++) {
if (visited[arr[i]]) {
repeating = arr[i];
}
else {
visited[arr[i]] = true;
}
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
missing = i;
break;
}
}
System.out.println("Repeating : " + repeating);
System.out.println("Missing : " + missing);
}
public static void main(String[] args)
{
int[] arr = { 7, 3, 4, 5, 5, 6, 2 };
printTwoElements(arr);
}
}
Python
def print_two_elements(arr):
n = len(arr)
# Creating visited vector of size n+1 with
# initial values as false. Note that array
# values will go upto n, that is why we
# have taken the size as n+1
visited = [False] * (n + 1)
repeating = -1
missing = -1
for i in range(n):
if visited[arr[i]]:
repeating = arr[i]
else:
visited[arr[i]] = True
for i in range(1, n + 1):
if not visited[i]:
missing = i
break
print(f"Repeating : {repeating}")
print(f"Missing : {missing}")
arr = [7, 3, 4, 5, 5, 6, 2]
print_two_elements(arr)
C#
using System;
class Program {
static void PrintTwoElements(int[] arr)
{
int n = arr.Length;
// Creating visited vector of size n+1 with
// initial values as false. Note that array
// values will go upto n, that is why we
// have taken the size as n+1
bool[] visited = new bool[n + 1];
int repeating = -1, missing = -1;
for (int i = 0; i < n; i++) {
if (visited[arr[i]]) {
repeating = arr[i];
}
else {
visited[arr[i]] = true;
}
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
missing = i;
break;
}
}
Console.WriteLine("Repeating : " + repeating);
Console.WriteLine("Missing : " + missing);
}
static void Main()
{
int[] arr = { 7, 3, 4, 5, 5, 6, 2 };
PrintTwoElements(arr);
}
}
Javascript
function printTwoElements(arr) {
const n = arr.length;
// Creating visited vector of size n+1 with
// initial values as false. Note that array
// values will go upto n, that is why we
// have taken the size as n+1
const visited = new Array(n + 1).fill(false);
let repeating = -1;
let missing = -1;
for (let i = 0; i < n; i++) {
if (visited[arr[i]]) {
repeating = arr[i];
} else {
visited[arr[i]] = true;
}
}
for (let i = 1; i <= n; i++) {
if (!visited[i]) {
missing = i;
break;
}
}
console.log("Repeating :", repeating);
console.log("Missing :", missing);
}
const arr = [7, 3, 4, 5, 5, 6, 2];
printTwoElements(arr);
OutputRepeating : 5
Missing : 1
Time Complexity: O(n)
Auxiliary Space: O(n)
Calculate the sum of the first size natural numbers. Traverse the array. While traversing, use the absolute value of every element as an index and make the value at this index negative to mark it visited and subtract this value from the missing variable. If something is already marked negative, then this is the repeating element. After traversing, the ‘missing’ variable holds the value of the missing element.
C++
#include <bits/stdc++.h>
using namespace std;
void printTwoElements(vector<int>& arr)
{
int n = arr.size();
int missing = (n * (n + 1)) / 2;
cout << "Repeating ";
for (int i = 0; i < n; i++) {
if (arr[abs(arr[i]) - 1] > 0)
{
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
missing -= abs(arr[i]); // subtract unique elements
}
else
cout << abs(arr[i]) << "\n";
}
cout << "Missing " << missing;
}
/* Driver code */
int main()
{
vector<int> arr = { 7, 3, 4, 5, 5, 6, 2 };
printTwoElements(arr);
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void printTwoElements(int* arr, int n) {
int missing = (n * (n + 1)) / 2;
printf("Repeating ");
for (int i = 0; i < n; i++) {
if (arr[abs(arr[i]) - 1] > 0) {
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
missing -= abs(arr[i]); // subtract unique elements
} else {
printf("%d\n", abs(arr[i]));
}
}
printf("Missing %d\n", missing);
}
/* Driver code */
int main() {
int arr[] = { 7, 3, 4, 5, 5, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printTwoElements(arr, n);
return 0;
}
Java
public class Main {
public static void printTwoElements(int[] arr) {
int n = arr.length;
int missing = (n * (n + 1)) / 2;
System.out.print("Repeating ");
for (int i = 0; i < n; i++) {
int absVal = Math.abs(arr[i]);
if (arr[absVal - 1] > 0) {
arr[absVal - 1] = -arr[absVal - 1];
missing -= absVal; // subtract unique elements
} else {
System.out.println(absVal);
}
}
System.out.println("Missing " + missing);
}
public static void main(String[] args) {
int[] arr = { 7, 3, 4, 5, 5, 6, 2 };
printTwoElements(arr);
}
}
Python
def print_two_elements(arr):
n = len(arr)
missing = (n * (n + 1)) // 2
print("Repeating", end=" ")
for i in range(n):
if arr[abs(arr[i]) - 1] > 0:
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]
missing -= abs(arr[i]) # subtract unique elements
else:
print(abs(arr[i]))
print("Missing", missing)
# Driver code
arr = [7, 3, 4, 5, 5, 6, 2]
print_two_elements(arr)
C#
using System;
class Program
{
public static void PrintTwoElements(int[] arr)
{
int n = arr.Length;
int missing = (n * (n + 1)) / 2;
Console.Write("Repeating ");
for (int i = 0; i < n; i++)
{
int absValue = Math.Abs(arr[i]);
if (arr[absValue - 1] > 0)
{
arr[absValue - 1] = -arr[absValue - 1];
missing -= absValue; // subtract unique elements
}
else
{
Console.WriteLine(absValue);
}
}
Console.WriteLine("Missing " + missing);
}
static void Main()
{
int[] arr = { 7, 3, 4, 5, 5, 6, 2 };
PrintTwoElements(arr);
}
}
Javascript
function printTwoElements(arr) {
let n = arr.length;
let missing = (n * (n + 1)) / 2; // sum of N
console.log("Repeating");
for (let i = 0; i < n; i++) {
let absValue = Math.abs(arr[i]);
if (arr[absValue - 1] > 0) {
arr[absValue - 1] = -arr[absValue - 1];
missing -= absValue; // subtract unique elements
} else {
console.log(absValue);
}
}
console.log("Missing " + missing);
}
// Driver code
let arr = [7, 3, 4, 5, 5, 6, 2];
printTwoElements(arr);
PHP
<?php
function printTwoElements($arr) {
$n = count($arr);
$missing = ($n * ($n + 1)) / 2; // sum of N
echo "Repeating ";
for ($i = 0; $i < $n; $i++) {
$absValue = abs($arr[$i]);
if ($arr[$absValue - 1] > 0) {
$arr[$absValue - 1] = -$arr[$absValue - 1];
$missing -= $absValue; // subtract unique elements
} else {
echo $absValue . "\n";
}
}
echo "Missing " . $missing . "\n";
}
// Driver code
$arr = array(7, 3, 4, 5, 5, 6, 2);
printTwoElements($arr);
?>
OutputRepeating 5
Missing 1
Time Complexity: O(n)
Auxiliary Space: O(1) as it is using constant variables
Making Two Math Equations:
- Let x be the missing and y be the repeating element.
- Let N is the size of the array.
- Get the sum of all numbers using the formula S = N(N+1)/2
- Get the sum of square of all numbers using formula SSq = N(N+1)(2N+1)/6
- Iterate through a loop from i = 1….N and do the following : S -= A[i], SSq -= (A[i]*A[i])
- It will give two equations
x – y = S
x^2 – y^2 = SSq
x + y = (SSq/S)
C++
#include <bits/stdc++.h>
using namespace std;
void repeatedNumber(const 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;
cout << "Repeating : " << repeating << endl;
cout << "Missing " << missing;
}
int main(void) {
vector<int> arr = {4, 3, 6, 2, 1, 6, 7};
repeatedNumber(arr);
return 0;
}
C
#include <stdio.h>
void repeatedNumber(int arr[], int n) {
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 < n; i++) {
s -= arr[i];
ssq -= arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
printf("Repeating : %d\n", repeating);
printf("Missing : %d\n", missing);
}
int main(void) {
int arr[] = {4, 3, 6, 2, 1, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
repeatedNumber(arr, n);
return 0;
}
Java
public class Main {
public static void repeatedNumber(int[] arr) {
int n = arr.length;
long s = (long) (n * (n + 1)) / 2;
long ssq = (long) (n * (n + 1) * (2 * n + 1)) / 6;
long missing = 0, repeating = 0;
for (int i = 0; i < n; i++) {
s -= arr[i];
ssq -= (long) arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
System.out.println("Repeating : " + repeating);
System.out.println("Missing : " + missing);
}
public static void main(String[] args) {
int[] arr = {4, 3, 6, 2, 1, 6, 7};
repeatedNumber(arr);
}
}
Python
def print_two_elements(arr):
n = len(arr)
s = (n * (n + 1)) // 2
ssq = (n * (n + 1) * (2 * n + 1)) // 6
missing = 0
repeating = 0
for i in range(n):
s -= arr[i]
ssq -= arr[i] * arr[i]
missing = (s + ssq // s) // 2
repeating = missing - s
print("Repeating:", repeating)
print("Missing:", missing)
arr = [4, 3, 6, 2, 1, 6, 7]
print_two_elements(arr)
C#
using System;
class Program
{
public static void PrintTwoElements(int[] arr)
{
int n = arr.Length;
long s = (long)(n * (n + 1)) / 2;
long ssq = (long)(n * (n + 1) * (2 * n + 1)) / 6;
long missing = 0, repeating = 0;
for (int i = 0; i < n; i++)
{
s -= arr[i];
ssq -= (long)arr[i] * arr[i];
}
missing = (s + ssq / s) / 2;
repeating = missing - s;
Console.WriteLine("Repeating : " + repeating);
Console.WriteLine("Missing : " + missing);
}
static void Main()
{
int[] arr = { 4, 3, 6, 2, 1, 6, 7 };
PrintTwoElements(arr);
}
}
Javascript
function printTwoElements(arr) {
let n = arr.length;
let s = (n * (n + 1)) / 2;
let ssq = (n * (n + 1) * (2 * n + 1)) / 6;
let missing = 0;
let repeating = 0;
for (let i = 0; i < n; i++) {
s -= arr[i];
ssq -= arr[i] * arr[i];
}
missing = (s + Math.floor(ssq / s)) / 2;
repeating = missing - s;
console.log("Repeating:", repeating);
console.log("Missing:", missing);
}
let arr = [4, 3, 6, 2, 1, 6, 7];
printTwoElements(arr);
OutputRepeating : 6
Missing 5
Time Complexity: O(n)
Auxiliary Space: O(1)
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:
- Let x and y be the desired output elements.
- Calculate the XOR of all the array elements.
xor1 = arr[0]^arr[1]^arr[2]…..arr[n-1]
- XOR the result with all numbers from 1 to n
xor1 = xor1^1^2^…..^n
- In the result xor1, all elements would nullify each other except x and y. All the bits that are set in xor1 will be set in either x or y. So if we take any set bit (We have chosen the rightmost set bit in code) of xor1 and divide the elements of the array in two sets â one set of elements with the same bit set and another set with the same bit not set. By doing so, we will get x in one set and y in another set. Now if we do XOR of all the elements in the first set, we will get x, and by doing the same in the other set we will get y.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
void getTwoElements(vector<int>& arr) {
int n = arr.size();
int xor1 = 0; // Will hold xor of all elements
// and numbers from 1 to n
int set_bit_no;
int x = 0, y = 0;
// Get the xor of all array elements
// And numbers from 1 to n
for (int i = 0; i < n; i++) {
xor1 ^= arr[i];
xor1 ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
set_bit_no = xor1 & ~(xor1 - 1);
// 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] & set_bit_no) { x ^= arr[i]; }
else { y ^= arr[i]; }
// Decide whether (i+1) is in first set
// or second
if ((i+1) & set_bit_no) { x ^= (i + 1); }
else { y ^= (i + 1); }
}
// Print the results
cout << "Missing and Repeating (In any order) "
<< x << " " << y;
}
int main() {
vector<int> arr = { 1, 3, 4, 5, 5, 6, 2 };
getTwoElements(arr);
return 0;
}
C
#include <stdio.h>
void getTwoElements(int arr[], int n) {
int xor1 = 0; // Will hold xor of all elements and numbers from 1 to n
int set_bit_no;
int x = 0, y = 0;
// Get the xor of all array elements and numbers from 1 to n
for (int i = 0; i < n; i++) {
xor1 ^= arr[i];
xor1 ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
set_bit_no = xor1 & ~(xor1 - 1);
// 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] & set_bit_no) { x ^= arr[i]; }
else { y ^= arr[i]; }
// Decide whether (i+1) is in first set or second
if ((i+1) & set_bit_no) { x ^= (i + 1); }
else { y ^= (i + 1); }
}
// Print the results
printf("Missing and Repeating (In any order): %d %d\n", x, y);
}
int main() {
int arr[] = { 1, 3, 4, 5, 5, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
getTwoElements(arr, n);
return 0;
}
Java
public class Main {
public static void getTwoElements(int[] arr) {
int n = arr.length;
int xor1 = 0; // Will hold xor of all
// elements and numbers from 1 to n
int set_bit_no;
int x = 0, y = 0;
// Get the xor of all array elements
// and numbers from 1 to n
for (int i = 0; i < n; i++) {
xor1 ^= arr[i];
xor1 ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
set_bit_no = xor1 & ~(xor1 - 1);
// 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] & set_bit_no) != 0) { x ^= arr[i]; }
else { y ^= arr[i]; }
// Decide whether (i+1) is in first set or second
if (((i+1) & set_bit_no) != 0) { x ^= (i + 1); }
else { y ^= (i + 1); }
}
// Print the results
System.out.println("Missing and Repeating (In any order): " + x + " " + y);
}
public static void main(String[] args) {
int[] arr = { 1, 3, 4, 5, 5, 6, 2 };
getTwoElements(arr);
}
}
Python
def get_two_elements(arr):
n = len(arr)
# Will hold xor of all elements
# and numbers from 1 to n
xor1 = 0
x = 0
y = 0
# Get the xor of all array elements
# and numbers from 1 to n
for i in range(n):
xor1 ^= arr[i]
xor1 ^= (i + 1) # 1 to n numbers
# Get the rightmost set bit in xor1
set_bit_no = xor1 & ~(xor1 - 1)
# 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] & set_bit_no:
x ^= arr[i]
else:
y ^= arr[i]
# Decide whether (i+1) is
# in first set or second
if (i + 1) & set_bit_no:
x ^= (i + 1)
else:
y ^= (i + 1)
# Print the results
print(f"Missing and Repeating (In any order): {x} {y}
C#
using System;
class Program
{
public static void GetTwoElements(int[] arr)
{
int n = arr.Length;
// Will hold xor of all elements and numbers from 1 to n
int xor1 = 0;
int x = 0, y = 0;
// Get the xor of all array elements and numbers from 1 to n
for (int i = 0; i < n; i++)
{
xor1 ^= arr[i];
xor1 ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
int set_bit_no = xor1 & ~(xor1 - 1);
// 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] & set_bit_no) != 0)
x ^= arr[i];
else
y ^= arr[i];
// Decide whether (i+1) is in first set or second
if (((i + 1) & set_bit_no) != 0)
x ^= (i + 1);
else
y ^= (i + 1);
}
// Print the results
Console.WriteLine("Missing and Repeating (In any order): " + x + " " + y);
}
static void Main()
{
int[] arr = { 1, 3, 4, 5, 5, 6, 2 };
GetTwoElements(arr);
}
}
Javascript
function getTwoElements(arr) {
let n = arr.length;
let xor1 = 0; // Will hold xor of all elements and numbers from 1 to n
let x = 0, y = 0;
// Get the xor of all array elements and numbers from 1 to n
for (let i = 0; i < n; i++) {
xor1 ^= arr[i];
xor1 ^= (i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
let set_bit_no = xor1 & ~(xor1 - 1);
// 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] & set_bit_no) {
x ^= arr[i];
} else {
y ^= arr[i];
}
// Decide whether (i+1) is in first set or second
if ((i + 1) & set_bit_no) {
x ^= (i + 1);
} else {
y ^= (i + 1);
}
}
// Print the results
console.log("Missing and Repeating (In any order):", x, y);
}
// Driver code
let arr = [1, 3, 4, 5, 5, 6, 2];
getTwoElements(arr);
PHP
<?php
function getTwoElements($arr) {
$n = count($arr);
$xor1 = 0; // Will hold xor of all elements
// and numbers from 1 to n
$x = 0;
$y = 0;
// Get the xor of all array elements
// and numbers from 1 to n
for ($i = 0; $i < $n; $i++) {
$xor1 ^= $arr[$i];
$xor1 ^= ($i + 1); // 1 to n numbers
}
// Get the rightmost set bit in xor1
$set_bit_no = $xor1 & ~($xor1 - 1);
// Now divide elements into two sets
// by comparing rightmost set bit
for ($i = 0; $i < $n; $i++) {
// Decide whether arr[i] is in first set or second
if ($arr[$i] & $set_bit_no) {
$x ^= $arr[$i];
} else {
$y ^= $arr[$i];
}
// Decide whether (i+1) is in first set or second
if (($i + 1) & $set_bit_no) {
$x ^= ($i + 1);
} else {
$y ^= ($i + 1);
}
}
// Print the results
echo "Missing and Repeating (In any order): $x $y\n";
}
// Driver code
$arr = array(1, 3, 4, 5, 5, 6, 2);
getTwoElements($arr);
?>
OutputMissing and Repeating (In any order) 7 5
Time Complexity: O(n)
Auxiliary Space: O(1) as it is using constant space if the input array is excluded
This method doesn’t cause overflow and does not modify the array, but it doesn’t tell which one occurs twice and which one is missing. We can add one more step that checks which one is missing and which one is repeating. This can be easily done in O(n) time.