Find missing elements from an Array with duplicates
Last Updated :
12 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem