Find missing elements from an Array with duplicates
Last Updated :
17 Jan, 2023
Given an array arr[] of size N having integers in the range [1, N] with some of the elements missing. The task is to find the missing elements.
Note: There can be duplicates in the array.
Examples:
Input: arr[] = {1, 3, 3, 3, 5}, N = 5
Output: 2 4
Explanation: The numbers missing from the list are 2 and 4
All other elements in the range [1, 5] are present in the array.
Input: arr[] = {1, 2, 3, 4, 4, 7, 7}, N = 7
Output: 5 6
Approach 1(Negating visited elements): The idea to solve the problem is as follows
In the given range [1, N] there should be an element corresponding to each index. So mark the visited indices by multiplying that element with -1. If an element is missing then its index will have a positive element. Otherwise, it will have a negative element.
Follow the below illustration:
Illustration:
Consider arr[] = {1, 3, ,3, 3, 5}
Here for illustration, we will use 1 based indexing
For i = 1:
=> arr[i] = 1. So mark arr[1] visited.
=> arr[1] = -1*arr[1] = -1*1 = -1
=> arr[] = {-1, 3, 3, 3, 5}
For i = 2:
=> arr[i] = 3. So mark arr[3] visited.
=> arr[3] = -1*arr[3] = -1*3 = -3
=> arr[] = {-1, 3, -3, 3, 5}
For i = 3:
=> arr[i] = -3. So we should move to absolute value of -3 i.e. 3
=> arr[3] is already visited. Skip to next index
=> arr[] = {-1, 3, -3, 3, 5}
For i = 4:
=> arr[i] = 3. So mark arr[3] visited.
=> arr[3] is already visited. Skip to next index
=> arr[] = {-1, 3, -3, 3, 5}
For i = 5:
=> arr[i] = 5. So mark arr[5] visited.
=> arr[5] = -1*arr[5] = -1*5 = -5
=> arr[] = {-1, 3, -3, 3, -5}
Again traverse the array. See that arr[2] and arr[4] are not visited.
So the missing elements are {2, 4}.
Follow the below steps to implement the idea:
- Traverse the array from i = 0 to N-1:
- If the element is negative take the positive value (say x = abs(arr[i])).
- if the value at (x-1)th index is not visited i.e., it is still positive then multiply that element with -1.
- Traverse the array again from i = 0 to N-1:
- If the element is not visited, i.e., has a positive value, push (i+1) to the resultant array.
- Return the resultant array that contains the missing elements.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the missing elements
vector<int> missing_elements(vector<int> vec)
{
// Vector to store the list
// of missing elements
vector<int> mis;
// For every given element
for (int i = 0; i < vec.size(); i++) {
// Find its index
int temp = abs(vec[i]) - 1;
// Update the element at the found index
vec[temp] = vec[temp] > 0
? -vec[temp] : vec[temp];
}
for (int i = 0; i < vec.size(); i++)
// Current element was not present
// in the original vector
if (vec[i] > 0)
mis.push_back(i + 1);
return mis;
}
// Driver code
int main()
{
vector<int> vec = { 3, 3, 3, 5, 1 };
// Vector to store the returned
// list of missing elements
vector<int> miss_ele = missing_elements(vec);
// Print the list of elements
for (int i = 0; i < miss_ele.size(); i++)
cout << miss_ele[i] << " ";
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// C implementation of the approach
#include <stdio.h>
#include <stdlib.h>
// Function to find the missing elements
void missing_elements(int vec[], int n)
{
int mis[n];
for (int i = 0; i < n; i++)
mis[i] = -1;
// For every given element
for (int i = 0; i < n; i++) {
// Find its index
int temp = abs(vec[i]) - 1;
// Update the element at the found index
vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp];
}
// Current element was not present
// in the original vector
for (int i = 0; i < n; i++)
if (vec[i] > 0)
mis[i] = (i + 1);
int miss_ele_size = sizeof(mis) / sizeof(mis[0]);
for (int i = 0; i < miss_ele_size; i++) {
if (mis[i] != -1)
printf("%d ", mis[i]);
}
}
// Driver code
int main()
{
int vec[] = { 3, 3, 3, 5, 1 };
int vec_size = sizeof(vec) / sizeof(vec[0]);
missing_elements(vec, vec_size);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java implementation of the above approach
import java.util.*;
class GFG {
// Function to find the missing elements
static List<Integer>
missing_elements(List<Integer> vec)
{
// Vector to store the list
// of missing elements
List<Integer> mis = new ArrayList<Integer>();
// For every given element
for (int i = 0; i < vec.size(); i++) {
// Find its index
int temp = Math.abs((int)vec.get(i)) - 1;
// Update the element at the found index
if ((int)vec.get(temp) > 0)
vec.set(temp, -(int)vec.get(temp));
else
vec.set(temp, vec.get(temp));
}
for (int i = 0; i < vec.size(); i++) {
// Current element was not present
// in the original vector
if ((int)vec.get(i) > 0)
mis.add(i + 1);
}
return mis;
}
// Driver code
public static void main(String args[])
{
List<Integer> vec = new ArrayList<Integer>();
vec.add(3);
vec.add(3);
vec.add(3);
vec.add(5);
vec.add(1);
// Vector to store the returned
// list of missing elements
List<Integer> miss_ele = missing_elements(vec);
// Print the list of elements
for (int i = 0; i < miss_ele.size(); i++)
System.out.print(miss_ele.get(i) + " ");
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# Python3 implementation of the approach
# Function to find the missing elements
def missing_elements(vec):
# Vector to store the list
# of missing elements
mis = []
# For every given element
for i in range(len(vec)):
# Find its index
temp = abs(vec[i]) - 1
# Update the element at the found index
if vec[temp] > 0:
vec[temp] = -vec[temp]
for i in range(len(vec)):
# Current element was not present
# in the original vector
if (vec[i] > 0):
mis.append(i + 1)
return mis
# Driver code
if __name__ == '__main__':
vec = [3, 3, 3, 5, 1]
# Vector to store the returned
# list of missing elements
miss_ele = missing_elements(vec)
# Print the list of elements
for i in range(len(miss_ele)):
print(miss_ele[i], end=" ")
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG {
// Function to find the missing elements
static List<int> missing_elements(List<int> vec)
{
// List<int> to store the list
// of missing elements
List<int> mis = new List<int>();
// For every given element
for (int i = 0; i < vec.Count; i++) {
// Find its index
int temp = Math.Abs((int)vec[i]) - 1;
// Update the element at the found index
if ((int)vec[temp] > 0)
vec[temp] = -(int)vec[temp];
else
vec[temp] = vec[temp];
}
for (int i = 0; i < vec.Count; i++) {
// Current element was not present
// in the original vector
if ((int)vec[i] > 0)
mis.Add(i + 1);
}
return mis;
}
// Driver code
public static void Main(String[] args)
{
List<int> vec = new List<int>();
vec.Add(3);
vec.Add(3);
vec.Add(3);
vec.Add(5);
vec.Add(1);
// List to store the returned
// list of missing elements
List<int> miss_ele = missing_elements(vec);
// Print the list of elements
for (int i = 0; i < miss_ele.Count; i++)
Console.Write(miss_ele[i] + " ");
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript implementation of the approach
// Function to find the missing elements
function missing_elements(vec)
{
// Vector to store the list
// of missing elements
let mis = [];
// For every given element
for (let i = 0; i < vec.length; i++) {
// Find its index
let temp = Math.abs(vec[i]) - 1;
// Update the element at the found index
vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp];
}
for (let i = 0; i < vec.length; i++)
// Current element was not present
// in the original vector
if (vec[i] > 0)
mis.push(i + 1);
return mis;
}
let vec = [ 3, 3, 3, 5, 1 ];
// Vector to store the returned
// list of missing elements
let miss_ele = missing_elements(vec);
// Print the list of elements
for (let i = 0; i < miss_ele.length; i++)
document.write(miss_ele[i] + " ");
</script>
Time Complexity: O(N).
Auxiliary Space: O(N)
Approach 2 (Performing in-place sorting): The idea in this case, is to use in-place sorting.
In the given range [1, N] there should be an element corresponding to each index. So we can sort them and then if at any index the position and the element are not same, those elements are missing.
For sorting the elements in linear time see the below pseudo code:
Pseudo Code:
Algorithm:
Start
Set pointer i = 0
while i < N:
pos = arr[i] - 1
If arr[pos] = pos + 1: // the element is in the correct position
i++
Else: // swap it to correct position
swap(arr[pos], arr[i])
end if
end while
for i = 0 to N-1:
If Arr[i] = i+1:
continue
Else:
i+1 is missing.
end if
end for
End
Follow the illustration below for a better understanding:
Illustration:
Consider arr[] = {3, 3, 3, 5, 1}
Example on how to sort in linear sort
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the missing elements
vector<int> FindMissing(vector<int> arr)
{
int i = 0;
int N = arr.size();
while (i < N) {
// as 0 based indexing
int correct = arr[i] - 1;
if (arr[i] != arr[correct]) {
swap(arr[i], arr[correct]);
}
else {
i++;
}
}
vector<int> ans;
for (i = 0; i < N; i++) {
if (arr[i] != i + 1) {
ans.push_back(i + 1);
}
}
return ans;
}
// Driver code
int main()
{
vector<int> arr = { 1, 3, 3, 3, 5 };
// Function call
vector<int> res = FindMissing(arr);
for(int x: res)
cout << x << " ";
return 0;
}
// Code done by R.Balakrishnan (rbkraj000)
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class GFG
{
// Driver code
public static void main(String[] args)
{
int[] arr = { 1, 3, 3, 3, 5 };
System.out.println(FindMissing(arr));
}
static public List<Integer>FindMissing(int[] arr)
{
int i = 0;
// Here we are using cyclic sort to sort the array
while (i < arr.length) {
int correct = arr[i] - 1;
// Finding correct index
if (arr[i] != arr[correct])
{
// calling swap function
swap(arr, i, correct);
}
else {
i++;
}
}
// just find missing number
// Making List to store the potential answer
List<Integer> ans = new ArrayList<>();
for (int index = 0; index < arr.length; index++) {
if (arr[index] != index + 1) {
ans.add(index + 1);
}
}
return ans;
}
// This is the swap function
static void swap(int[] arr, int first, int second)
{
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}
// This code is contributed by --> Karan Hora (karansinghyoyo)
Python3
# Python code to implement the approach
# Function to find the missing elements
def FindMissing(arr):
i = 0
N = len(arr)
while(i < N):
# as 0 based indexing
correct = arr[i] - 1
if(arr[i] != arr[correct]):
temp = arr[i]
arr[i] = arr[correct]
arr[correct] = temp
else:
i += 1
ans = []
for i in range(N):
if(arr[i] != i+1):
ans.append(i+1)
return ans
arr = [1, 3, 3, 3, 5]
# Function call
res = FindMissing(arr)
for x in range(len(res)):
print(res[x], end=" ")
# This code is contributed by lokeshmvs21.
C#
// C# code to implement the approach
using System;
using System.Collections;
public class GFG {
// Function to find the missing elements
static public ArrayList FindMissing(int[] arr)
{
int i = 0;
// Here we are using cyclic sort to sort the array
while (i < arr.Length) {
int correct = arr[i] - 1;
// Finding correct index
if (arr[i] != arr[correct]) {
// calling swap function
swap(arr, i, correct);
}
else {
i++;
}
}
// just find missing number
// Making List to store the potential answer
ArrayList ans = new ArrayList();
for (int index = 0; index < arr.Length; index++) {
if (arr[index] != index + 1) {
ans.Add(index + 1);
}
}
return ans;
}
// This is the swap function
static void swap(int[] arr, int first, int second)
{
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
static public void Main()
{
// Code
int[] arr = { 1, 3, 3, 3, 5 };
ArrayList res = FindMissing(arr);
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i] + " ");
}
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// JS code to implement the approach
// Function to find the missing elements
function FindMissing(arr)
{
let i = 0;
let N = arr.length;
while (i < N) {
// as 0 based indexing
let correct = arr[i] - 1;
if (arr[i] != arr[correct]) {
let temp = arr[i];
arr[i] = arr[correct];
arr[correct = temp];
}
else {
i++;
}
}
let ans = []
for (i = 0; i < N; i++) {
if (arr[i] != i + 1) {
ans.push(i + 1);
}
}
return ans;
}
// Driver code
let arr = [ 1, 3, 3, 3, 5 ];
// Function call
let res = FindMissing(arr);
console.log(res);
// This code is contributed by akashish__
Time Complexity: O(N)
Even in the worst case, there will be N-1 Swaps + N-1 Comparisons done. So asymptotically it's O(N).
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read