Find duplicate elements in an array
Last Updated :
19 Dec, 2024
Given an array of n integers. The task is to find all elements that have more than one occurrences. The output should only be one occurrence of a number irrespective of the number of occurrences in the input array.
Examples:
Input: {2, 10, 10, 100, 2, 10, 11, 2, 11, 2}
Output: {2, 10, 11}
Input: {5, 40, 1, 40, 100000, 1, 5, 1}
Output: {5, 40, 1}
Note: Duplicate elements can be printed in any order.
Naive Approach - O(n^2) Time and O(1) Space
The idea is to use a nested loop and for each element check if the element is present in the array more than once or not. If present, then check if it is already added to the result. If not, then add to the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> findDuplicates(vector<int>& arr) {
vector<int> res;
for (int i = 0; i < arr.size() - 1; i++) {
for (int j = i + 1; j < arr.size(); j++) {
if (arr[i] == arr[j]) {
// Check if the duplicate element is already in res
auto it = find(res.begin(), res.end(), arr[i]);
if (it == res.end()) {
// Add the element to res if not already present
res.push_back(arr[i]);
}
// Move to the next element in arr
break;
}
}
}
return res;
}
int main()
{
vector<int> arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
vector<int> duplicates = findDuplicates(arr);
for (int i = 0; i < duplicates.size(); i++)
cout << duplicates[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
static List<Integer> findDuplicates(int[] arr) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
// Check if the duplicate element is already in res
if (!res.contains(arr[i])) {
res.add(arr[i]);
}
break;
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
List<Integer> duplicates = findDuplicates(arr);
for (int x : duplicates) {
System.out.print(x + " ");
}
}
}
Python
def findDuplicates(arr):
res = []
for i in range(len(arr) - 1):
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
# Check if the duplicate element is already in res
if arr[i] not in res:
res.append(arr[i])
break
return res
# Driver code
if __name__ == "__main__":
arr = [12, 11, 40, 12, 5, 6, 5, 12, 11]
duplicates = findDuplicates(arr)
for x in duplicates:
print(x, end=' ')
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> findDuplicates(int[] arr) {
List<int> res = new List<int>();
for (int i = 0; i < arr.Length - 1; i++) {
for (int j = i + 1; j < arr.Length; j++) {
if (arr[i] == arr[j]) {
// Check if the duplicate element is already in res
if (!res.Contains(arr[i])) {
// Add the element to res if not already present
res.Add(arr[i]);
}
// Move to the next element in arr
break;
}
}
}
return res;
}
static void Main() {
int[] arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
List<int> duplicates = findDuplicates(arr);
for (int i = 0; i < duplicates.Count; i++) {
Console.Write(duplicates[i] + " ");
}
}
}
JavaScript
function findDuplicates(arr) {
let res = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
// Check if the duplicate element is already in res
if (!res.includes(arr[i])) {
// Add the element to res if not already present
res.push(arr[i]);
}
// Move to the next element in arr
break;
}
}
}
return res;
}
const arr = [12, 11, 40, 12, 5, 6, 5, 12, 11];
const duplicates = findDuplicates(arr);
for (let i = 0; i < duplicates.length; i++) {
console.log(duplicates[i] + " ");
}
Better Approach - Use Sorting and Binary Search - O(n Log n) Time and O(1) Space
- Sort the array.
- For every element, find indexes of its first and last occurrences using binary search.
- If both indexes are same, then this element is having only one occurrence, so we ignore this element.
- Else, we add this element to result and move the index to last index of this element plus 1.
C++
// C++ program to find the duplicate elements using Binary Search
#include <bits/stdc++.h>
using namespace std;
vector<int> findDuplicates(vector<int>& arr) {
sort(arr.begin(), arr.end());
vector<int> res;
int i = 0;
while (i < arr.size()) {
// Index of first and last occurrence of arr[i]
// using binary search
int first = lower_bound(arr.begin(), arr.end(), arr[i]) - arr.begin();
int last = upper_bound(arr.begin(), arr.end(), arr[i]) - arr.begin() - 1;
// If the element occurs more than once, add it to res
if (last > first) {
res.push_back(arr[i]);
}
// Update i to the last index
// of the current element
i = last + 1;
}
return res;
}
int main() {
vector<int> arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
vector<int> res = findDuplicates(arr);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
// Java program to find the duplicate elements using Binary Search
import java.util.*;
class GfG {
// Returns index of the first occurrence of target
static int lowerBound(int[] arr, int target) {
int low = 0, high = arr.length;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] < target)
low = mid + 1;
else
high = mid;
}
return low;
}
// Returns index just past the last occurrence of target
static int upperBound(int[] arr, int target) {
int low = 0, high = arr.length;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] <= target)
low = mid + 1;
else
high = mid;
}
return low;
}
// Function to return elements that occur in arr more than once
static List<Integer> findDuplicates(int[] arr) {
Arrays.sort(arr);
List<Integer> res = new ArrayList<>();
int i = 0;
while (i < arr.length) {
int first = lowerBound(arr, arr[i]);
int last = upperBound(arr, arr[i]) - 1;
// If the element occurs more than once, add it to res
if (last > first) {
res.add(arr[i]);
}
// Update i to the last index of the current element
i = last + 1;
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
List<Integer> res = findDuplicates(arr);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Python program to find the duplicate elements using
# Binary Search
# Index of the first occurrence of target
def lowerBound(arr, target):
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < target:
low = mid + 1
else:
high = mid
return low
# Index just past the last occurrence of target
def upperBound(arr, target):
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] <= target:
low = mid + 1
else:
high = mid
return low
def findDuplicates(arr):
arr.sort()
res = []
i = 0
while i < len(arr):
first = lowerBound(arr, arr[i])
last = upperBound(arr, arr[i]) - 1
# If the element occurs more than once, add it to res
if last > first:
res.append(arr[i])
# Update i to the last index of the current element
i = last + 1
return res
# Driver code
if __name__ == "__main__":
arr = [12, 11, 40, 12, 5, 6, 5, 12, 11]
res = findDuplicates(arr)
for x in res:
print(x, end=' ')
C#
// C# program to find the duplicate elements using
// Binary Search
using System;
using System.Collections.Generic;
class GfG {
static int lowerBound(int[] arr, int target) {
int left = 0;
int right = arr.Length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target)
left = mid + 1;
else
right = mid;
}
return left;
}
static int upperBound(int[] arr, int target) {
int left = 0;
int right = arr.Length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] <= target)
left = mid + 1;
else
right = mid;
}
return left;
}
static List<int> findDuplicates(int[] arr) {
Array.Sort(arr);
List<int> duplicates = new List<int>();
for (int i = 0; i < arr.Length; i++) {
int lower = lowerBound(arr, arr[i]);
int upper = upperBound(arr, arr[i]);
if (upper - lower > 1)
duplicates.Add(arr[i]);
// Skip to the next unique element
i = upper - 1;
}
return duplicates;
}
static void Main() {
int[] arr = { 12, 11, 40, 12, 5, 6, 5, 12, 11 };
List<int> duplicates = findDuplicates(arr);
foreach (int num in duplicates)
Console.Write(num + " ");
}
}
JavaScript
// JavaScript program to find the duplicate elements using
// Binary Search
function findDuplicates(arr) {
arr.sort();
let res = [];
let i = 0;
while (i < arr.length) {
// Index of first and last occurrence of arr[i]
// using binary search
let first = arr.indexOf(arr[i]);
let last = arr.lastIndexOf(arr[i]);
// If the element occurs more than once, add it to res
if (last > first) {
res.push(arr[i]);
}
// Update i to the last index
// of the current element
i = last + 1;
}
return res;
}
const arr = [12, 11, 40, 12, 5, 6, 5, 12, 11];
const res = findDuplicates(arr);
for (let i = 0; i < res.length; i++)
console.log(res[i] + " ");
Expected Approach - O(n) Time and O(n) Space
We use hashing. Count frequency of occurrence of each element and the elements with frequency more than 1 is printed. unordered map is used as range of integers is not known. For Python, Use Dictionary to store number as key and it's frequency as value. Dictionary can be used as range of integers is not known.
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> findDuplicates(vector<int>& arr) {
// Find frequency of every element
unordered_map<int, int> freq;
for (int x : arr)
freq[x]++;
// Move all those elements to resul that
// have frequency more than 1.
vector<int> res;
for (auto& entry : freq) {
if (entry.second > 1)
res.push_back(entry.first);
}
return res;
}
int main() {
vector<int> arr = {12, 11, 40, 12, 5, 6, 5, 12, 11};
vector<int> res = findDuplicates(arr);
for (int num : res) {
cout << num << " ";
}
return 0;
}
Java
import java.util.*;
class GfG {
static List<Integer> findDuplicates(List<Integer> arr) {
// Find frequency of every element
Map<Integer, Integer> freq = new HashMap<>();
for (int x : arr) {
freq.put(x, freq.getOrDefault(x, 0) + 1);
}
// Move all those elements to result that
// have frequency more than 1.
List<Integer> res = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
if (entry.getValue() > 1) {
res.add(entry.getKey());
}
}
return res;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(12, 11, 40, 12, 5, 6, 5, 12, 11);
List<Integer> res = findDuplicates(arr);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
from collections import defaultdict
def findDuplicates(arr):
# Find frequency of every element
freq = defaultdict(int)
for x in arr:
freq[x] += 1
# Move all those elements to result that
# have frequency more than 1.
res = [x for x in freq if freq[x] > 1]
return res
if __name__ == "__main__":
arr = [12, 11, 40, 12, 5, 6, 5, 12, 11]
res = findDuplicates(arr)
for x in res:
print(x, end=' ')
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static List<int> findDuplicates(List<int> arr) {
// Find frequency of every element
var freq = arr.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
// Move all those elements to resul that
// have frequency more than 1.
var res = freq.Where(entry => entry.Value > 1).Select(entry => entry.Key).ToList();
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 12, 11, 40, 12, 5, 6, 5, 12, 11 };
List<int> res = findDuplicates(arr);
foreach (int num in res) {
Console.Write(num + " ");
}
}
}
JavaScript
function findDuplicates(arr) {
// Find frequency of every element
let freq = {};
for (let x of arr)
freq[x] = (freq[x] || 0) + 1;
// Move all those elements to resul that
// have frequency more than 1.
let res = [];
for (let entry in freq) {
if (freq[entry] > 1)
res.push(parseInt(entry));
}
return res;
}
let arr = [12, 11, 40, 12, 5, 6, 5, 12, 11];
let res = findDuplicates(arr);
for (let num of res) {
console.log(num + " ");
}
Related Post :
Print All Distinct Elements of a given integer array
Find duplicates in O(n) time and O(1) extra space | Set 1
Duplicates in an array in O(n) and by using O(1) extra space | Set-2
Print all the duplicates in the input string
Similar Reads
Find missing elements from an Array with duplicates 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 = 5Output: 2 4Explanation: The numbers missing from the list are 2 a
12 min read
Find the only different element in an array Given an array of integers where all elements are same except one element, find the only different element in the array. It may be assumed that the size of the array is at least two.Examples: Input : arr[] = {10, 10, 10, 20, 10, 10} Output : 3 arr[3] is the only different element.Input : arr[] = {30
10 min read
Find element in array that divides all array elements Given an array of n non-negative integers. Find such element in the array, that all array elements are divisible by it. Examples : Input : arr[] = {2, 2, 4}Output : 2 Input : arr[] = {2, 1, 3, 1, 6}Output : 1 Input: arr[] = {2, 3, 5}Output : -1 Brute Force Approach: The brute force approach to solve
7 min read
Searching Elements in an Array | Array Operations In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as: Searching in an Unsorted Array using Linear SearchSearching in a Sorted Array using Linear SearchSearching in a Sorted Array using Binary SearchSearching in an Sorted Array using Fibona
15+ min read
Find a Fixed Point in an array with duplicates allowed Given an array of n duplicates or distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the
8 min read
Peak Element in Array Given an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them.Note: Consider the element befo
12 min read
Array range queries for searching an element Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included). Prerequisite : Mo's Algorithms Examples : Input : N = 5 arr = [1, 1, 5, 4, 5] Q = 3 1 3 2 2 5 1 3 5 5 Output : No Yes Yes Expla
15+ min read
Find an array element such that all elements are divisible by it Given an array of numbers, find the number among them such that all numbers are divisible by it. If not possible print -1. Examples: Input : arr = {25, 20, 5, 10, 100} Output : 5 Explanation : 5 is an array element which divides all numbers. Input : arr = {9, 3, 6, 2, 15} Output : -1 Explanation : N
8 min read
Find all elements in array which have at-least two greater elements Given an array of n distinct elements, the task is to find all elements in array which have at-least two greater elements than themselves. Examples : Input : arr[] = {2, 8, 7, 1, 5};Output : 2 1 5 Explanation:The output three elements have two or more greater elements Explanation:Input : arr[] = {7,
11 min read