Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find duplicate elements in an array
Next article icon

Find duplicate elements in an array

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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] + " "); } 

Output
12 11 5 

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] + " ");   

Output
5 11 12 

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 + " "); } 

Output
12 11 5 

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


Next Article
Find duplicate elements in an array

A

Ayush Jauhari
Improve
Article Tags :
  • Hash
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Hash

Similar Reads

    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences